gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:14:40 25 4
gpt4 key购买 nike

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

  1. 我的第一个解决方案是在主 Activity 暂停时执行“stopService()”,但这会阻止音乐在其他 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();
}

我开始/停止服务:

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

附言感谢所有的回答,但正如我所说,onStop 方法会在我更改 Activity 时停止音乐,这是我不想要的。

最佳答案

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

更多信息:Stop MediaPlayer service when app goes in Background

关于java - 如何在应用程序进入后台时停止服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50797300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com