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

查看:184
本文介绍了当应用程序进入后台时停止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();
}

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

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.

我试图在 onStop 中停止播放 onDestroy 方法,但这会在我改变活动时停止音乐,这是我不想要的(我希望音乐在用户浏览活动时继续播放)。

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 of music服务和接收事件的方法:

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

    }
};

在Application类中,我这样做了:

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

和BroadcastReceiver:

and in the BroadcastReceiver:

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天全站免登陆