gpt4 book ai didi

java - 应用程序关闭后服务内的功能停止

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

该服务始终在后台运行,但由于某种原因,我的函数 saveUserLocation(); 一段时间后停止。当应用程序打开时,它会一直运行。这是一些图片,显示在我关闭应用程序后服务仍在后台运行,另一张图片是我关闭应用程序,然后 logD 仍然打印几秒钟,然后停止。

后台服务

service

LogD -> logcat 突然停止

logcat

来自服务的代码

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: called");

notificationGenerator();
getLocation();
return START_NOT_STICKY;
}

private void getLocation() {
// ---------------------------------- LocationRequest ------------------------------------
// Create the location request to start receiving updates
LocationRequest mLocationRequestHighAccuracy = new LocationRequest();
mLocationRequestHighAccuracy.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequestHighAccuracy.setInterval(UPDATE_INTERVAL);
mLocationRequestHighAccuracy.setFastestInterval(FASTEST_INTERVAL);
mFusedLocationClient.requestLocationUpdates(mLocationRequestHighAccuracy, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
Log.d(TAG, "(*) Service Running");
}
},
Looper.myLooper()); // Looper.myLooper tells this to repeat forever until thread is destroyed
}

list

<service android:name=".service.Service"
android:enabled="true"
android:exported="true"/>

Logcat 中没有显示任何错误,它只是停止,当我再次启动应用程序时,它会继续。知道它为什么停止吗?

最佳答案

当应用程序关闭时,服务也会关闭。因为它们在一个线程中,所以服务应该在另一个线程上运行,这样它就不能被关闭,所以有两种方法来激活服务。

1:使用报警管理器(按照此[ https://stackoverflow.com/a/34790376/8918150][1] )

2:您还可以使用startForeground()。这是一个很好的方法

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

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