如何在屏幕锁定或休眠时暂停和播放媒体播放器?

How to pause and play media player when screen is locked or sleeps?

我正在使用 Java 和 xml 创建暑期申请。这个应用程序有背景音乐,我想暂停然后播放,具体取决于它所处的状态。当我锁定屏幕时,音乐不会暂停,它会继续播放。我该如何解决这个问题,我已尝试使用此站点上的方法:

https://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents

我一直未能成功获得工作原型,我在 android 工作室工作。

        myPlayer = MediaPlayer.create(c(this is the context), myField(This is the raw file));
        myPlayer.start();
        myPlayer.setLooping(true);
        myPlayer.setVolume(0.7f,0.7f);

我可以添加什么来在按下锁定按钮或 phone 进入睡眠状态时暂停媒体播放器,然后在 phone 解锁时播放它?

    @Override
    protected void onPause() {
        super.onPause();

        if (myPlayer != null) {
            myPlayer.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (myPlayer != null) {
            myPlayer.start();
        }
    }