简体   繁体   English

我怎样才能避免死于背景工作

[英]How can I prevent from death my background process

I have the following problem: 我有以下问题:

My android application requires some setup, which can take several minutes. 我的Android应用程序需要一些设置,这可能需要几分钟。 It is executed only once at the time of first launch. 首次启动时仅执行一次。 So, when a new user starts the application for the first time, a special initializing process starts and a progress dialog with caption "Preparation for the first launch" appears. 因此,当新用户首次启动该应用程序时,将启动一个特殊的初始化过程,并显示标题为“首次启动的准备”的进度对话框。 When this step is complete, it isn't needed next time. 完成此步骤后,下次就不需要了。

The problem is, that while this process is being executed, the user can switch to another activity - to start another application or make a call. 问题是,在执行此过程时,用户可以切换到另一个活动-启动另一个应用程序或进行呼叫。 And it entails the death of this setup process. 并且这将导致设置过程的终止。 What should I do to avoid this? 我应该怎么做才能避免这种情况?

Take into account, that this setup process is run in IntentService. 考虑到此设置过程在IntentService中运行。 However it doesn't help. 但是,这没有帮助。

Thank you in advance. 先感谢您。

You can't prevent a Service from getting killed. 您无法防止Service被杀死。 You can however start it with the flag START_STICKY . 但是,您可以使用标志START_STICKY来启动它。 Then it will be restarted as soon as there are free capacities again. 然后,一旦再次有可用容量,它将重新启动。

You'd need to save it's state somehow though. 您需要以某种方式保存它的状态。 You can use eg onDestroy for that. 您可以使用例如onDestroy

You could also look here for some tricks how to make it more likely that your service survives. 您也可以在这里寻找一些技巧,以使您的服务更有可能存活。

Thank you, guys! 感谢大伙们! With help of @F43nd1r I found the satisfactory solution: at the start of my process I call startForeground() and it prevents the service from death. 在@ F43nd1r的帮助下,我找到了令人满意的解决方案:在我的过程开始时,我调用了startForeground(),它可以防止服务中断。 Then, at the end, I call stopForeground(). 然后,最后,我调用stopForeground()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM