My app crash only in vivo phones, and the error log is this:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getOpPackageName()' on a null object reference at android.media.PlayerBase.PlaybackDetectionCallBack(PlayerBase.java:348) at android.media.PlayerBase.baseStop(PlayerBase.java:229) at android.media.MediaPlayer$2.onCompletion(MediaPlayer.java:3578) at android.media.MediaPlayer$EventHandler.handleMessage(MediaPlayer.java:3351) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:192) at android.app.ActivityThread.main(ActivityThread.java:6671) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:818)
I believe it is about MediaPlayer
which I use to play BGM in my app.
But I can't find out how this happens since the error stack didn't retrieve to my code.
Here is all my code about play BGM.
public void playBgm(final int resId, boolean restartIfSame) {
if(resId == currentBgmRes && !restartIfSame) {
if(!bgmPlayer.isPlaying()) {
bgmPlayer.start();
}
return;
}
if(bgmPlayer.isPlaying()) {
bgmPlayer.stop();
}
_playBgm(resId);
}
private void _playBgm(int resId) {
bgmPlayer.release();
bgmPlayer = MediaPlayer.create(this, resId);
bgmPlayer.setLooping(true);
currentBgmRes = resId;
bgmPlayer.start();
}
The two functions are inside class AppDelegate extends Application
, so this
should be the application instance.
It doesn't always crash. Since the phone causing the problem is some far-away user's, I can't get the phone in several days. So I'm not sure in what situation it will happen, but it should not happen in any situation.
I figured out the problem.
My MediaPlayer
variable has an initial value new MediaPlayer()
.
When the Activity
playing the BGM calls onPause()
, I call MediaPlayer.pause()
.
But calling pause()
to a new MediaPlayer()
seems to cause crash in some devices, while OK in other devices.
I change the initial value to null
, and do the null check whenever I use the object. The crash never happen again.