当应用程序关闭时,Android 服务停止 [英] Android Service Stops When App Is Closed

查看:54
本文介绍了当应用程序关闭时,Android 服务停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从我的主要 Android Activity 启动服务,如下所示:

I am starting a service from my main Android activity as follows:

final Context context = base.getApplicationContext();
final Intent intent = new Intent(context, MyService.class);
startService(intent);

当我通过从最近的应用程序列表中将其滑出来关闭活动页面时,该服务停止运行并在一段时间后重新启动.由于我的应用程序要求,我无法使用带有通知的持久服务.如何让服务不重启或关闭,而是在应用退出时继续运行?

When I close the activity page by swiping it out from the recent apps list, the service stops running and restarts after some time. I can't use persistent services with notifications because of my app requirements. How can I make the service NOT restart or shutdown and just keep on running on app exit?

推荐答案

我遇到了同样的情况,到目前为止我了解到当应用程序关闭时服务也会关闭,因为它们在一个线程中,所以服务应该在另一个线程上,以便它不会被关闭,查看并查看使用警报管理器保持服务的活动状态,这里是一个示例 http://www.vogella.com/articles/AndroidServices/article.html 这样您的服务就不会显示在通知中.

I'm in the same situation, so far I learned when the app is closed the service get closed also because they are in a one thread, so the service should be on another thread in order fot it not to be closed, look into that and look into keeping the service alive with alarm manager here an example http://www.vogella.com/articles/AndroidServices/article.html this way your service won't be shown in notification.

最后,在我完成所有研究之后,我开始意识到长期运行服务的最佳选择是 startForeground(),因为它是为此而设计的,而且系统实际上很好地处理了您的服务.

lastly, after all the research I've done I'm coming to realize that the best choice for a long running service is startForeground(), because it is made for that and the system actually deals with your service well.

这篇关于当应用程序关闭时,Android 服务停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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