且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当应用程序进入后台时停止 MediaPlayer 服务

更新时间:2022-12-27 11:13:53

播放器停止后需要重新准备.如果您想在您的应用程序进入后台时停止播放,并在您的应用程序进入前台时从头开始播放媒体.只需将您的 BroadcastReceiver 代码修改为:

You need to prepare the player again after stopping it. If you want to stop the playback when your app goes in background, and start the media from the beginning when your app comes into foreground. Just modify your BroadcastReceiver code to this:

private BroadcastReceiver StateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String status = intent.getStringExtra("status");
            if (parseInt(String.valueOf(status)) == 0) {
                player.stop();
            } else {
                player = MediaPlayer.create(this, R.raw.music);
                player.setLooping(true);
                player.start();
            }

        }
    };

但是,如果您想暂停播放并从您离开的地方继续播放,请进行以下更改:在您的 Application 类中,在 onActivityDestroyed() 中:

However, if you want to pause the playback and resume it from where you left, then make the following changes: In your Application class, in onActivityDestroyed():

@Override
public void onActivityDestroyed(Activity activity) {
    send_status(2);
}

在广播接收器中:

private BroadcastReceiver StateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String status = intent.getStringExtra("status");
            if (parseInt(String.valueOf(status)) == 0) {
                player.pause();  //When app is in background and not killed, we just want to pause the player and not want to lose the current state.
            } else if (parseInt(String.valueOf(status)) == 1) {
                if (player != null)
                    player.start();  // If the player was created and wasn't stopped, it won't be null, and the playback will be resumed from where we left of.
                else {
                    // If the player was stopped, we need to prepare it once again.
                    player = MediaPlayer.create(this, R.raw.music);
                    player.setLooping(true);
                    player.start();
                }
            } else if(player != null){
                player.stop();
                player.release();
            }

        }
    };

另外,请查看 MediaPlayer 状态.