当应用程序在后台时,如何在 BaseActivity 中使用 onPause 停止音乐(MediaPlayer)

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

我可以用这个播放音乐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();
    }

所以我的活动可以通过这个 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);
    }

它工作正常,但当我的应用程序在后台时它仍然继续播放... 我知道如何停止和暂停它,但我怎么能不在 activity 中而是在基础 Activity 中对所有活动执行此操作? 我的基地 activity 看起来像这样

public class BaseActivity extends AppCompatActivity {

    MediaPlayer player;

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

我的 activity 扩展了 BaseActivity...

但是背景音乐还在播放...

您需要像这样在 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();
        }

}

现在你的音乐activity应该是这样

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);
    }

}