2012-11-16 25 views
1

初學者在這裏。我有一個類中有一個SoundPool對象。我想讓這個類實現Parcelable,以便它的實例可以在活動之間傳遞(這樣我只加載一次聲音)。如何將SoundPool對象讀入並寫入Parcel?

但我在將SoundPool對象寫入包裹時遇到問題。我可以知道它是否有可能? (也許SoundPool不實施Parcelable?)

public class SoundSamples { // implements Parcelable{ 

SoundPool sound; 
AudioManager am; 
int soundId[] = new int[4]; 
Context ctxt; 

public SoundSamples(Context context) { 
    ctxt = context; 
} 

public void makeSound() { 
    Context context = ctxt; 

    sound = new SoundPool(10, AudioManager.STREAM_MUSIC, 0); 
    soundId[0] = sound.load(context, R.raw.c4, 0); 
    soundId[1] = sound.load(context, R.raw.cs4, 0); 
    soundId[2] = sound.load(context, R.raw.d4, 0); 
    soundId[3] = sound.load(context, R.raw.ds4, 0); 
} 

public SoundPool getSound() { 
    return sound; 
} 

public int[] getSoundId() { 
    return soundId; 
} 

/* 
private SoundSamples(Parcel in) { 

    // STUCK HERE 
    sound = in.readParcelable(null); 
    soundId = in.readArray(Integer); 
} 

public static final Parcelable.Creator<SoundSamples> CREATOR 
= new Parcelable.Creator<SoundSamples>() { 
    public SoundSamples createFromParcel(Parcel in) { 
     return new SoundSamples(in); 
    } 

    public SoundSamples[] newArray(int size) { 
     return new SoundSamples[size]; 
    } 
}; 

public void writeToParcel(Parcel out, int flags) { 

     // AND STUCK HERE 
    out.writeIntArray(soundId); 
    out.writeParcelable((Parcelable)sound,0); 
} 
*/ 
} 

任何幫助表示讚賞。請指出這是否是正確的做事方式。謝謝。

回答

0

你絕對要做不是想要將SoundPool轉換爲Parcel並在活動之間發送它。這是完全沒有效率的。

只需將SoundPool對象存儲在public static變量中,並且您可以從所有活動中訪問它。

欲瞭解更多信息,請參閱我的回答Intent and Parcelable object Android