gpt4 book ai didi

java - 关闭应用程序后服务停止运行

转载 作者:行者123 更新时间:2023-12-01 16:42:23 25 4
gpt4 key购买 nike

我在 Android 中编写了一个简单的服务。只要应用程序正在运行,它就会运行,并在应用程序关闭时停止。我的代码如下:

public class WitoService extends Service {
private MediaPlayer mp;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//return super.onStartCommand(intent, flags, startId);
mp=MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
mp.setLooping(true);
mp.start();
return START_STICKY;
}

@Override
public void onDestroy() {
super.onDestroy();
mp.stop();
}

}

list 文件条目

<service android:name=".WitoService"/>

服务调用代码:

if(!serviceRunning) {
startService(new Intent(this, WitoService.class));
serviceRunning=true;
}else {
stopService(new Intent(this, WitoService.class));
serviceRunning=false;
}

enter code here

最佳答案

当您的应用程序目标大于 android O 时,这是正常行为。为了使您的服务保持 Activity 状态,应该创建前台服务并通过通知通知用户。你可以在这里查看 https://developer.android.com/about/versions/oreo/background#services

While an app is in the foreground, it can create and run both foreground and background services freely. When an app goes into the background, it has a window of several minutes in which it is still allowed to create and use services. At the end of that window, the app is considered to be idle. At this time, the system stops the app's background services, just as if the app had called the services' Service.stopSelf() methods.

关于java - 关闭应用程序后服务停止运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61838174/

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