当应用程序进入后台时停止 MediaPlayer 服务 [英] Stop MediaPlayer service when app goes in Background

查看:36
本文介绍了当应用程序进入后台时停止 MediaPlayer 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个媒体播放器服务,可以在我的应用程序的后台播放音乐,例如:

I have a media player service that plays music in the background of my app throughout activities like :

public class Music extends Service {
MediaPlayer player;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

public void onCreate() {
    player = MediaPlayer.create(this, R.raw.music);
    player.setLooping(true);
}

public int onStartCommand(Intent intent, int flags, int startId) {
    player.start();
    return Service.START_NOT_STICKY;
}


public void onDestroy() {
    player.stop();
    player.release();
    stopSelf();
    super.onDestroy();
}

问题是当用户更换应用程序或进入手机主屏幕(应用程序进入后台)时,音乐仍在播放.

The problem is that when the user changes app or goes to home screen of phone(app goes in the background) the music is still playing.

我试图在 onStoponDestroy 方法中停止它,但是当我改变活动时这会停止音乐,这是我不想要的(我想要在用户浏览活动时继续播放音乐).

I have tried to stop it in onStop and onDestroy method but this stops the music when I change activities which is something that I don't want(I want the music to keep playing when user navigates through activities).

更新

我尝试使用广播:

我添加了

LocalBroadcastManager.getInstance(this).registerReceiver(StateReceiver, new IntentFilter("status"));

在音乐服务的onCreate和接收事件的方法中:

in onCreate of music Service and a method to receive events :

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.start();}

    }
};

在应用程序类中,我这样做了:

And in Application class I did this:

public class app_class extends Application implements Application.ActivityLifecycleCallbacks {
private static int resumed;
private static int paused;

private static String currentActivity;

@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
    currentActivity = activity.getClass().getSimpleName();
}
public static String getCurrentActivity() {
    return currentActivity;
}
@Override
public void onActivityStarted(Activity activity) {
}
 @Override
public void onActivityResumed(Activity activity) {
    send_status(1);
}

@Override
public void onActivityPaused(Activity activity) {
    send_status(0);
}  
 private void send_status(int status_counter) {
    Intent intent = new Intent("status");
    intent.putExtra("status", String.valueOf(status_counter));
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
@Override
public void onActivityStopped(Activity activity) {      

}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

}
@Override
public void onActivityDestroyed(Activity activity) {

}   

但是音乐不会恢复

推荐答案

播放器停止后需要重新准备.如果您想在您的应用程序进入后台时停止播放,并在您的应用程序进入前台时从头开始播放媒体.只需将您的 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 状态.

这篇关于当应用程序进入后台时停止 MediaPlayer 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆