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

你。 提交于 2021-01-01 13:51:09

问题


I am using Java and xml to create an application for the summer. This app has music in the background, that I would like to pause and then play depending on the state it is in. When i lock my screen the music does not pause it keeps playing. How would i fix this, I have tried to use the method on this site:

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

I have not been able to successfully get a working prototype, and I am working in android studio.

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

What could I add to pause the mediaplayer when the lock button is pressed or the phone goes to sleep and then play it when the phone is unlocked?


回答1:


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

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

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


来源:https://stackoverflow.com/questions/44264994/how-to-pause-and-play-media-player-when-screen-is-locked-or-sleeps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!