如何在应用程序进入后台时停止服务

How to Stop service when app goes in background

我有一个多 activity 应用程序。在主要 activity 中启动了一个播放音乐的服务。当我浏览活动时,音乐仍在播放(这是我想要的)但是当我单击主页按钮并且应用程序进入后台时音乐仍在播放(这是我不想要的)。

  1. 我的第一个解决方案是 'stopService()' onPause of main activity 但这会阻止音乐在其他活动中播放。

  2. 在onStop方法中尝试了同样的方法,出现了同样的问题。

: 如何在整个应用程序进入后台时停止播放音乐(停止服务)?

我的服务代码:

public class MediaService extends Service {
private MediaPlayer player;

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    player = MediaPlayer.create(this, R.raw.music);
    player.setLooping(true);
    player.start();
    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();

    player.stop();
}

我 start/stop 服务于:

 music_intent = new Intent(this, MediaService.class);
 startService(music_intent);
 stopService(music_intent);

P.S。感谢所有的答案,但正如我所说,当我更改活动时,onStop 方法会停止音乐,这是我不想要的。

根据 Activity lifecicle,您应该使用 onStop() 停止播放音频

记住 onStop()

May never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.

所以这样做应该可以解决您的问题

@Override
public void onStop() {
    super.onStop();

     if(player.isPlaying()){
        player.stop();
        player.release();
        }
}

使用 onStop() 或 onPause() 停止服务而不是 onDestroy();

onStop() - 当应用进入背景时(不可见)

onPause() - 当任何弹出窗口出现时

是实际答案,试试这个。 出于某种原因,当应用程序进入后台时服务没有停止

它在您的 stopService() 调用之前很久就停止了,因为一旦 onHandleIntent() 返回,它就在创建后几毫秒停止了。

不会停止的是您的计时器,它在后台线程上运行并将继续运行直到您取消它或您的进程终止。

恕我直言,这是对 IntentService 的不当使用。如果你想控制生命周期,使用一个服务,并在 onDestroy() 中停止后台工作。

在应用程序 class 中使用 Application.ActivityLifecycleCallbacks 的类似问题中找到此解决方案来检查应用程序何时进入后台,然后向服务发送广播以停止它。

更多内容: