Search code examples
androidonpause

Android - Continue Music Playing onPause


I have a few audio files that play for a minute or two in an application, similar to a soundboard. When someone clicks a button, it plays the sound. Simple enough. I have a setting in a SharedPreference that asks a user if when they exit or pause the application, if they'd like to keep the sound playing. That's where I'm stuck.

As of right now, when a user has it set to "keep playing," the application freezes and you have to force quit it manually. Here's what I have:

@Override
protected void onPause() {

    SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    boolean settingContinueMusic = getPrefs.getBoolean("continueMusic", false);
    if(settingContinueMusic == false){
        super.onPause();
        if(audio1.isPlaying()) { audio1.pause(); }
        if(audio2.isPlaying()) { audio2.pause(); }
        if(audio3.isPlaying()) { audio3.pause(); }
    }

}

Solution

  • I think the problem is happening because you have put super.onPause(); inside the if condition. It gets executed only if the user has decided o pause the audio. Move it out of if and see if it works.

    @Override
    protected void onPause() {
     super.onPause();
        SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        boolean settingContinueMusic = getPrefs.getBoolean("continueMusic", false);
        if(settingContinueMusic == false){
    
            if(audio1.isPlaying()) { audio1.pause(); }
            if(audio2.isPlaying()) { audio2.pause(); }
            if(audio3.isPlaying()) { audio3.pause(); }
        }
    
    }