Search code examples
javaandroidandroid-mediaplayerillegalstateexception

IllegalStateException in MediaPlayer#Pause


I uploaded my app at google console and in prelaunch report , in 2 devices only, there was this issue java.lang.IllegalStateException

FATAL EXCEPTION: ControllerMessenger
Process: com.wolframite.manos.crack_the_code, PID: 11744
java.lang.IllegalStateException
at android.media.MediaPlayer.isPlaying(Native Method)
at com.wolframite.manos.crack_the_code.Music$1.onReceive(Music.java:36)
at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:311)
at android.support.v4.content.LocalBroadcastManager.access$000(LocalBroadcastManager.java:47)
at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:120)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.support.test.espresso.base.Interrogator.a(Interrogator.java:19)
at android.support.test.espresso.base.UiControllerImpl.a(UiControllerImpl.java:142)
at android.support.test.espresso.base.UiControllerImpl.a(UiControllerImpl.java:134)
at android.support.test.espresso.base.UiControllerImpl.a(UiControllerImpl.java:34)
at android.support.test.espresso.action.MotionEvents.a(MotionEvents.java:74)
at android.support.test.espresso.action.MotionEvents.a(MotionEvents.java:52)
at android.support.test.espresso.action.Tap.c(Tap.java:9)
at android.support.test.espresso.action.Tap.a(Tap.java:19)
at android.support.test.espresso.action.Tap$1.b(Tap.java:2)
at android.support.test.espresso.action.GeneralClickAction.perform(GeneralClickAction.java:22)
at android.support.test.espresso.ViewInteraction$SingleExecutionViewAction.perform(ViewInteraction.java:9)
at android.support.test.espresso.ViewInteraction.a(ViewInteraction.java:78)
at android.support.test.espresso.ViewInteraction.a(ViewInteraction.java:94)
at android.support.test.espresso.ViewInteraction$1.call(ViewInteraction.java:3)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5459)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

I don't know what to do. What is this issue and what more do I need to upload to help solve this.

The music class which is used to play music in the app and receives a broadcast when app goes in background to stop music and when app goes in foreground to resume it where line 36 is player.pause() :

public class Music extends Service {
private MediaPlayer player;

@Override
public IBinder onBind(Intent intent) {
    return null;
}
public void onCreate() {
    player = MediaPlayer.create(this, R.raw.music);
    player.setLooping(true);
    LocalBroadcastManager.getInstance(this).registerReceiver(StateReceiver, new IntentFilter("status"));

}
private final BroadcastReceiver StateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String status = intent.getStringExtra("status");
        if (parseInt(String.valueOf(status)) == 0) {
            player.pause();
        } else if (parseInt(String.valueOf(status)) == 1) {
            if (player != null)
                player.start();
            else {
                player = MediaPlayer.create(Music.this, R.raw.music);
                player.setLooping(true);
                player.start();
            }
        } else if(player != null){
            player.stop();
            player.release();
        }

    }
};
public int onStartCommand(Intent intent, int flags, int startId) {
    player.start();
    return Service.START_NOT_STICKY;
}
public void onDestroy() {
    player.stop();
    player.release();
    LocalBroadcastManager.getInstance(this).unregisterReceiver(StateReceiver);
    stopSelf();
    super.onDestroy();

}

Solution

  • In order to avoid these type of errors you can create a utility class which acts as a secure wrapper around the MediaPlayer methods which sometimes throw unexpected exception and crash your app.

    I have used code in a class called MediaPlayerUtils like the example below to avoid these types of behaviours and add an extra layer of safety to my apps:

    public static void pause(MediaPlayer mediaPlayer) {
        if (mediaPlayer != null) {
            try {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                }
            } catch (Exception e) {
                Log.w(MediaPlayerUtil.class.getName(),
                        String.format("Failed to stop media player: %s", e));
            }
        }
    }
    

    You then have to use instead of:

    player.pause(); // not safe
    

    this code:

    MediaPlayerUtils.pause(player);  // safe
    

    You can add similar methods to the for MediaPlayer.stop(), like e.g:;

    public static void stop(MediaPlayer mediaPlayer) {
        if (mediaPlayer != null) {
            try {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                }
                resetRelease(mediaPlayer);
            } catch (Exception e) {
                Log.e(MediaPlayerUtil.class.getName(),
                        String.format("Failed to stop media player: %s", e));
            }
        }
    }