Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/213.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 应用程序关闭时服务停止_Android_Service - Fatal编程技术网

Android 应用程序关闭时服务停止

Android 应用程序关闭时服务停止,android,service,Android,Service,我需要一个服务在后台运行,并计算两个位置之间每分钟的距离。我使用线程来每分钟执行一个方法,然后我了解到当应用程序关闭时,服务也会停止,因为应用程序和服务使用相同的线程。 如何创建一个每1分钟调用一次的简单方法,即使在应用程序关闭的情况下也可以在后台调用?您必须为此使用线程,并在启动服务时设置一个标志。并检查停止服务的标志。您可以通过修改清单在单独的流程中运行服务 <service android:name="com.example.myapplication.MyBackgroun

我需要一个服务在后台运行,并计算两个位置之间每分钟的距离。我使用线程来每分钟执行一个方法,然后我了解到当应用程序关闭时,服务也会停止,因为应用程序和服务使用相同的线程。
如何创建一个每1分钟调用一次的简单方法,即使在应用程序关闭的情况下也可以在后台调用?

您必须为此使用线程,并在启动服务时设置一个标志。并检查停止服务的标志。

您可以通过修改清单在单独的流程中运行
服务

<service
    android:name="com.example.myapplication.MyBackgroundService"
    android:exported="false"
    android:process=":myBackgroundServiceProcess" >
</service>
这(和其他)选项将被解释。基本上
START\u STICKY
的意思是“嘿,安卓!如果你真的因为内存不足而不得不关闭我宝贵的服务,那么请尝试重新启动。”

START\u NOT\u STICKY
的意思是“不……不用麻烦了。如果我真的需要运行我的服务,我会自己再次调用startService()

这(开始粘)在大多数情况下可能是好的。您的服务将从头开始。如果这适合您的用例,您可以尝试一下

还有一些“前台服务”,它们不太可能被Android关闭,因为它们更像是可视应用。事实上,它们会在通知抽屉中显示一个图标和一条状态文本(如果您这样做的话)。因此,它们对用户可见,例如SportsTracker、Beddit等应用程序

这涉及到修改您的
服务
onStartCommand()

服务将照常启动,您可以通过以下操作退出前台模式:

myBackgroundService.stopForeground(true);

布尔参数定义了是否也应该取消通知。

这里有一个教程供您使用:非常好的解释第二种方法似乎是大多数应用程序执行此操作的方式。我非常感谢你,先生,你解决了数小时的谷歌搜索和文档整理。但是对于android 8.0,现在一切都改变了@马库斯
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    // Tapping the notification will open the specified Activity.
    Intent activityIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
            activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    // This always shows up in the notifications area when this Service is running.
    // TODO: String localization 
    Notification not = new Notification.Builder(this).
            setContentTitle(getText(R.string.app_name)).
            setContentInfo("Doing stuff in the background...").setSmallIcon(R.mipmap.ic_launcher).
            setContentIntent(pendingIntent).build();
    startForeground(1, not);

    // Other code goes here...

    return super.onStartCommand(intent, flags, startId);
}
myBackgroundService.stopForeground(true);