在android中通过滑动杀死应用程序时如何处理正在运行的服务? [英] How to handle running service when app is killed by swiping in android?

查看:39
本文介绍了在android中通过滑动杀死应用程序时如何处理正在运行的服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的应用程序正在运行并且我按下主页按钮,应用程序将进入后台.现在,如果我长按主页按钮并通过从最近的应用程序列表中滑动它来杀死该应用程序,则没有像 onPause()onStop() 之类的事件>onDestroy() 被调用而不是进程终止.因此,如果我希望我的服务停止、终止通知并取消注册侦听器,我该怎么做?我阅读了很多文章和博客,但没有得到任何有用的信息,也没有找到任何关于它的文档.任何帮助,将不胜感激.提前致谢.

If my app is running and i press home button, the app goes in background. Now if I long press the home button and kill the app by swiping it from the recent app list, none of the events like onPause(), onStop() or onDestroy() gets called rather the process is terminated. So if i want my services to stop, kill notifications and unregister listeners, how can i do that? I read quite a few articles and blogs but didn't get any useful information and I haven't found any documentation about it. Any help would be appreciated. Thanks in advance.

推荐答案

我刚刚解决了一个类似的问题.

I just resolved a similar kind of issue.

如果它只是停止服务,当应用程序通过从最近的应用程序列表中滑动而被杀死时,您可以执行以下操作.

Here is what you can do if its just about stopping service when application is killed by swiping from Recent app list.

在您的 Manifest 文件中,保持标记 stopWithTasktrue 以用于服务.喜欢:

Inside your Manifest file, keep flag stopWithTask as true for Service. Like:

<service
    android:name="com.myapp.MyService"
    android:stopWithTask="true" />

但正如您所说,您想取消注册侦听器并停止通知等,我建议采用这种方法:

But as you say you want to unregister listeners and stop notification etc, I would suggest this approach:

  1. 在您的 Manifest 文件中,将标记 stopWithTask 保留为 false 以用于服务.喜欢:

  1. Inside your Manifest file, keep flag stopWithTask as false for Service. Like:

<service
    android:name="com.myapp.MyService"
    android:stopWithTask="false" />

  • 现在在您的 MyService 服务中,覆盖方法 onTaskRemoved.(仅当 stopWithTask 设置为 false 时才会触发.

  • Now in your MyService service, override method onTaskRemoved. (This will be fired only if stopWithTask is set to false).

    public void onTaskRemoved(Intent rootIntent) {
    
        //unregister listeners
        //do any other cleanup if required
    
        //stop service
        stopSelf();  
    }
    

  • 请参阅我的问题以了解更多信息详细信息,其中也包含其他部分代码.

    Refer my question for more details, which contains other part of code, too.

    希望这会有所帮助.

    这篇关于在android中通过滑动杀死应用程序时如何处理正在运行的服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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