简体   繁体   English

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

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

I am using Java and xml to create an application for the summer. 我正在使用Java和xml在夏天创建一个应用程序。 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 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. 我无法成功获取可工作的原型,并且我正在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? 当按下锁定按钮或手机进入睡眠状态,然后在手机解锁时播放该媒体播放器,我可以添加哪些暂停媒体播放器的功能?

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM