我使用这个标准的 SoundManager。它在我的所有设备上都可以正常工作,但仅在市场上偶尔出现这些错误
SoundManager.playSound(SoundManager.java:87) 中的 NullPointerException
SoundManager.cleanup(SoundManager.java:107) 中的 NullPointerException
这是代码:
public class SoundManager {
private static SoundManager _instance;
private static SoundPool mSoundPool;
private static HashMap<Integer, Integer> mSoundPoolMap;
private static AudioManager mAudioManager;
private static Context mContext;
private SoundManager(){ }
static synchronized public SoundManager getInstance(){
if (_instance == null)
_instance = new SoundManager();
return _instance;
}
public static void initSounds(Context theContext){
mContext = theContext;
mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
mSoundPoolMap = new HashMap<Integer, Integer>();
mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
}
public static void addSound(int Index,int SoundID){
mSoundPoolMap.put(Index, mSoundPool.load(mContext, SoundID, 1));
}
public static void loadSounds(){
mSoundPoolMap.put(1, mSoundPool.load(mContext, R.raw.kick1, 1));
mSoundPoolMap.put(2, mSoundPool.load(mContext, R.raw.kick2, 1));
mSoundPoolMap.put(3, mSoundPool.load(mContext, R.raw.kick3, 1));
}
public static void playSound(int index, float volume){
**line 87:** float streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
streamVolume = streamVolume / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
mSoundPool.play(mSoundPoolMap.get(index), streamVolume*volume, streamVolume*volume, 1, 0, 1);
}
public static void stopSound(int index){
mSoundPool.stop(mSoundPoolMap.get(index));
}
public static void cleanup(){
**line 107:** mSoundPool.release();
mSoundPool = null;
mSoundPoolMap.clear();
mAudioManager.unloadSoundEffects();
_instance = null;
}
}
这是启动活动中的清理调用:
//REMOVE SOUND MEMORY ALLOCATION
@Override
public void onDestroy()
{
super.onDestroy();
SoundManager.cleanup();
}
有谁知道是什么导致了这些偶尔出现的罕见错误以及如何防止它们?这发生在我所有使用此 SoundManager 的应用程序中......即使有点奇怪的猜测也会有所帮助。