Takuya2412
Takuya2412

Reputation: 224

How to stop Music (MediaPlayer) with onPause in BaseActivity when App is on background

I can play music with this class

public class MusicPlayer extends AppCompatActivity {

    MediaPlayer player;

    public void play(Context c, @RawRes int sound){
        if (player == null){
            player = MediaPlayer.create(c, sound);
        }
        player.start();
    }

so my activities can play music by this onCreate

private MusicPlayer playboy = new MusicPlayer();

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        playboy.play(this, R.raw.song);
    }

It works fine but it still continue to play when my app is on the background... I know how to stop and pause it but how can I do this not IN the activity but in the Base Activity for all activities? My base activity looks like this

public class BaseActivity extends AppCompatActivity {

    MediaPlayer player;

    @Override
    protected void onPause() {
        super.onPause();
        if (player != null) {
            player.pause();
        }
    }

and my activity extends the BaseActivity...

But the music is still playing in the background...

Upvotes: 0

Views: 103

Answers (1)

Quick learner
Quick learner

Reputation: 11457

You need initialize media player like this in Base activity

public class BaseActivity extends AppCompatActivity {

    MediaPlayer player;


    public void play(Context c, @RawRes int sound){
            if (player == null){
                player = MediaPlayer.create(c, sound);
            }
            player.start();
        }

}

Now your music activity should be like this

public class MusicPlayer extends AppCompatActivity {



    @Override
    protected void onPause() {
        super.onPause();
// pause media player in onPause
        if (player != null) {
            player.pause();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
// play song in oncreate()
        player.play(this, R.raw.song);
    }

}

Upvotes: 1

Related Questions