IllegalStateException for MediaPlayer

2k views Asked by At

I have a game in which one can toggle sound on and off by a button. However, if sound is on, after onPause() and returning to onResume() to running, if the player tries to make an action, the game crashes. In contrast, on soundless mode, gameplay continues seamlessly.

This is the diagnosis generated by logcat:

Caused by:

java.lang.IllegalStateException
        at android.media.MediaPlayer._start(Native Method)
        at android.media.MediaPlayer.start(MediaPlayer.java:1143)
        at nocompany.rect.MainActivity.playSound(MainActivity.java:85)
        at nocompany.rect.MainActivity$1.run(MainActivity.java:165)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5105)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
        at dalvik.system.NativeStart.main(Native Method)

These are the relevant codes in my project:

MainActivity

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sound=MediaPlayer.create(this,R.raw.chaching);
}
public void playSound()
{
    if (!noSound)
    sound.start();
}
private boolean noSound=false;
public void noSound(View v){
    if (!noSound) {
        {
            noSound = !noSound;
            soundBut.setImageResource(R.drawable.nosound);
        }
    } else {
        noSound = !noSound;
        soundBut.setImageResource(R.drawable.sound);=

    }
}
1

There are 1 answers

0
Andy On BEST ANSWER

The issue is not explicitly displayed but arises due to what is NOT in onResume(). By having the MediaPlayer created in onCreate(), after returning from onPause(), the activity does not go through onCreate() and thus there is no MediaPlayer. To resolve this issue, one would put the setup for MediaPlayer in onResume().

This is the following code used to resolve the issue:

@Override
public void onResume() {
    super.onResume();
    sound=MediaPlayer.create(this,R.raw.chaching);
}