如何正确停止前台服务? [英] How to properly stop a foreground service?

查看:99
本文介绍了如何正确停止前台服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用startForeground在后台使我的服务持久"并且不会被操作系统杀死.
我通过调用stopForeground和stopService在主要活动的onDestroy方法中删除该服务.问题是,当我从最近的应用程序中删除我的应用程序以杀死它时,调试会话仍在运行,而在正常"功能(不使用startForeground)下,调试会话正确终止.
使用adb shell确认该应用程序仍在运行.
startForeground以某种方式创建了一个特殊的"运行线程,仅通过停止前台和服务就无法将其停止.
有什么想法吗?

I use startForeground to make my service "persist" in background and not be killed by the OS.
I remove the service in the main activity onDestroy method by calling stopForeground and stopService. The problem is, when I swipe my app off the recent apps to kill it, the debug session is still running, whereas in the "normal" functioning (without using startForeground), the debug session terminates correctly.
Using adb shell confirms that the app is still running.
startForeground somehow creates a "special" running thread that could not be stopped by simply stopping the foreground and the service.
Any ideas please ?

推荐答案

如果您要在从近期任务中清除应用程序时停止服务,则必须定义一个属性 stopWithTask 清单文件中的服务如下所示

if you want to stop your service when you are clearing your application from the recent task, you have to define an attribute stopWithTask for service in the manifest file like this as shown below

  <service
    android:enabled="true"
    android:name=".ExampleService"
    android:exported="false"
    android:stopWithTask="true" />

然后您可以在服务中覆盖onTaskRemoved方法,该方法将在应用程序任务清除后被调用

then you can override onTaskRemoved method in the service , this will be called when the application's task is cleared

@Override
    public void onTaskRemoved(Intent rootIntent) {
        System.out.println("onTaskRemoved called");
        super.onTaskRemoved(rootIntent);
        //do something you want
        //stop service
        this.stopSelf();
    }

这篇关于如何正确停止前台服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆