我正在构建一个音乐应用程序,它可以正常播放歌曲,但是最近,该应用程序将崩溃并显示错误:
尝试在空对象引用上调用接口方法'void vn.mymusic.android.store.media.player.Player.setOnAudioFocusChangedListener(vn.mymusic.android.store.media.player.Player $ OnAudioFocusChangedListener)'>
这种错误很少发生,但我真的很想知道为什么原因以及解决方案。
reset();
releaseAudioEffectors();
try {
if (mPlayer == null) {
mPlayer = mDetector.getPlayer(trackPath);
}
} catch (Exception e) {
}
if (mPlayer == null) {
LogEx.d(TAG, "Player not found:" + trackPath);
skipError();
return;
}
mPlayer.setAudioFocusEnable(true);
mPlayer.setOnAudioFocusChangedListener(this);
mPlayer.setOnPreparedListener(this);
mPlayer.setOnCompletionListener(this);
mPlayer.setOnInfoListener(this);
mPlayer.setOnErrorListener(this);
mPlayer.setOnSeekCompleteListener(this);
mPlayer.setNotificationIntentInfo(ACTION_PLAY, getPackageName(), PlayerFragment.class.getName(), Intent.FLAG_ACTIVITY_SINGLE_TOP);
mPlayer.setWakeMode(PowerManager.PARTIAL_WAKE_LOCK);
mPlayer.setOnMediaUpdatePlayCountListener(this);
OnAudioFocusChangeListener的替代方法
public void onAudioFocusChanged(int focusChange) {
LogEx.d(TAG, "onAudioFocusChanged()" + focusChange);
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
if (getStatus() == State.STARTED) {
mPlayer.clearNotificationIntentInfo();
mAudioFocusLoss = true;
pause();
}
break;
case AudioManager.AUDIOFOCUS_GAIN:
if (mAudioFocusLoss) {
mAudioFocusLoss = false;
setAutoStart(true);
start();
}
break;
default:
LogEx.e(TAG, "not handling audiofocus change :" + focusChange);
break;
}
}