1

I have an app with a button to play or pause music. Pressing the back button while playing music pauses it and opening the app again resumes the music after pressing the play button. But that doesn't work with home or recents button. The music pauses but upon reopening the app and pressing the play button doesn't play the music until a force close. Here is the code:

package com.example.firozkaoo2222.myapplication;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import static com.example.firozkaoo2222.myapplication.R.raw.police;

public class MainActivity extends AppCompatActivity {

private MediaPlayer policeSound = MediaPlayer.create(this, police);

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button policeSounds = this.findViewById(R.id.police);

    policeSounds.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (policeSound == null) {
                policeSound = MediaPlayer.create(getApplicationContext(), R.raw.police);
            }

            if (policeSound.isPlaying()) {
                policeSound.pause();
            } else {

                policeSound.start();
            }
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    if (policeSound != null) {
        policeSound = MediaPlayer.create(this, R.raw.police);
        policeSound.start();
    }

}

@Override
public void onPause() {
    super.onPause();
    if (policeSound.isPlaying())
        policeSound.pause();
}

//Back button pressed.
@Override
public void onBackPressed() {
    super.onBackPressed();
    if (policeSound.isPlaying())
        policeSound.pause();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    policeSound.stop();
    policeSound = null;
}

}

1 Answers1

0

If you press home button the app go to the background and when you came from the background you should override the method onResume();

Code:

public class MainActivity extends AppCompatActivity {

    //THIS IS YOUR LAST MISTAKE. IF YOU TRY TO CREATE THE OBJECT WITH THE CONTEXT AND THE RESOUERCES
    //WHEN THE ACTIVITY IS NOT CREATED YET, YOUR APP CRASH
    //private MediaPlayer policeSound = MediaPlayer.create(this, R.raw.police);
    private MediaPlayer policeSound;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button policeSounds = this.findViewById(R.id.police);

        policeSounds.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (policeSound == null) {
                    policeSound = MediaPlayer.create(getApplicationContext(), R.raw.police);
                }

                if (policeSound.isPlaying()) {
                    policeSound.pause();
                } else {

                    policeSound.start();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (policeSound != null) {
            policeSound = MediaPlayer.create(this, R.raw.police);
            policeSound.start();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        if (policeSound.isPlaying())
            policeSound.pause();
    }

    //Back button pressed.
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (policeSound.isPlaying())
            policeSound.pause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        policeSound.stop();
        policeSound = null;
    }
}

I hope this help you.

Juanjo Berenguer
  • 789
  • 1
  • 5
  • 8
  • it is gonna work because i think that the home button stop() the policesound , so you need to start() it again so that you can play() it or pause() it , but the return button doesn't actually stop() it. you might also want to check this issue https://stackoverflow.com/a/9161089/9504326 – Elhoussine Zennati Sep 06 '18 at 09:56
  • Thanks for such a fast response. I didn't get the expected results though. After changing the code, the music plays automatically upon opening the app(without pressing the play button). Back button works well though still the home and recents button have the same issue – Vipul Priyadarshi Sep 06 '18 at 09:57
  • @JuanjoBerenguer Doesn't work either.. Still the same just the sound plays automatically on opening the app – Vipul Priyadarshi Sep 06 '18 at 11:49
  • Opening the app when? When you came from background? When you start the app the first time? I am not able to understand what is happening. I will create a project later to understand it better. – Juanjo Berenguer Sep 06 '18 at 11:53
  • I modified the code in the answer, try it and say me something. – Juanjo Berenguer Sep 06 '18 at 13:17
  • I'm really sorry @JuanjoBerenguer . I only changed a few lines of code and ended up getting those errors. After changing the code entirely which was suggested by you, all the things are working properly. The hme , back and recents butons are working as I expected ( play or pause works perfectly all the time). But there is just one issue, the audio plays automatically just after launching the app (without even pressing the play button). Appreciate your help :) – Vipul Priyadarshi Sep 06 '18 at 18:16
  • You need create the media player object when you click the button the first time. That solves your problem. I a glad that I could help you. Happy coding dude – Juanjo Berenguer Sep 06 '18 at 18:27
  • @JuanjoBerenguer wouldn't be possible without you.. Thanks a lot! – Vipul Priyadarshi Sep 06 '18 at 18:55
  • @JuanjoBerenguer I get this error " lambda expression are not supported at language level 1.7" on this line "policeSounds.setOnClickListener(v -> {" – Vipul Priyadarshi Sep 07 '18 at 10:17
  • edited. This is because i am using Java 8 and that let you use lambda to make the code more clea. I editet the answer with the classic on click listener. I let you here an article about lamda in Android:https://code.tutsplus.com/tutorials/java-8-for-android-cleaner-code-with-lambda-expressions--cms-29661 – Juanjo Berenguer Sep 07 '18 at 10:21
  • @JuanjoBerenguer A new error pops up after changing the code. It says " Cannot resolve method 'create(anonymous android.view.View.OnCLickListener, int)' " at this line " public void onClick(View view) { if (policeSound == null){ policeSound = MediaPlayer.create(this,R.raw.police); //here to be specific " – Vipul Priyadarshi Sep 07 '18 at 10:31
  • Fixed. Sorry it was a typo, this was refering the View of the clicklistener instead the context of the app. Now should work – Juanjo Berenguer Sep 07 '18 at 10:35
  • @JuanjoBerenguer The build was successful but the installation says "App not installed" .Idk whats wrong here :| – Vipul Priyadarshi Sep 07 '18 at 10:47
  • I dont know Vipul. Try to uninstall the app in the phone, Clean and Rebuild and then Install – Juanjo Berenguer Sep 07 '18 at 10:49
  • @JuanjoBerenguer Thanks a lot for your time! I never knew people here at StackOverflow are so helpful ! – Vipul Priyadarshi Sep 07 '18 at 10:54
  • My pleasure, happy coding!4 – Juanjo Berenguer Sep 07 '18 at 10:55
  • @JuanjoBerenguer There's something wrong with code actually. I tried running the code on the emulator and the app just opens and closes. This is happening since the last change in code – Vipul Priyadarshi Sep 07 '18 at 17:13
  • Do me a favor, edit the question with your full code in the Activity. Just copy the full activity – Juanjo Berenguer Sep 07 '18 at 17:19
  • @JuanjoBerenguer Done. Have a look – Vipul Priyadarshi Sep 07 '18 at 18:27
  • It's working again hehe :D. I let you a comment in the code, it was your last mistake. – Juanjo Berenguer Sep 07 '18 at 18:44
  • @JuanjoBerenguer You the MVP! Thanks .. No more questions :) – Vipul Priyadarshi Sep 07 '18 at 18:58
  • I am glad that you finally has the media player. Happy coding dude – Juanjo Berenguer Sep 07 '18 at 19:01