如何留下一个活动时做的Andr​​oid手柄后台线程?手柄、线程、后台、Andr

2023-09-04 08:29:22 作者:让伤疤微疼

我需要我的Andr​​oid应用程序,以节省它的状态保存到磁盘时,它的活动被放在后台或死亡。它已经建议我启动一个线程时的onPause()被调用,并执行任何昂贵的I / O过程存在(见http://stackoverflow.com/questions/3894668/saving-loading-document-state-quickly-and-robustly-for-image-editor).

在什么情况下会在OS杀死线程,以及如何共同做这些情况出现?

我认为这将是怎么样的活动涉及了操作系统可以任意决定要杀死线程,但会大多只有做到这一点,当资源是极其有限的。这将是很好找到这虽然一些特定的文档。

这是玩弄,用一些测试code,后台线程开始的onPause()将在我的设备上后台运行下去(我尝试加载大量的应用程序,不能让它被杀死)。

有关我的具体的应用程序,我写在这里我使用了Command模式和备忘录模式允许撤销和重做编辑的位图编辑器。我希望用户能够撤销/重做的编辑甚至如用户得到一个电话呼叫,当它被放在背景中的活性被杀死。我能想到的最好的解决方法是使用一个后台线程应用程序中使用的不断救我的命令,并纪念对象到磁盘,并完成了拯救那些留在后台线程,如果在onPause被调用的任何对象。在最坏的情况下,如果线程被杀害我只是失去了一些修改。

解决方案   

在什么情况下会在OS杀死线程,以及如何共同做这些情况出现?

该操作系统不会杀线程,除非它被杀死的过程 - Android不与你自己创建的线程的东西。如果你是前台进程,你就不会被撞死。 Android系统中,你失去的前景在几秒钟内杀死进程的可能性(在的onPause())是微乎其微。工艺生命周期的文档 - 什么就有什么的吧 - 可以发现here.

I need my Android app to save it's state to disk when its activity is put in the background or killed. It's been suggested that I start a thread when onPause() is called and perform any expensive I/O procedures there (see http://stackoverflow.com/questions/3894668/saving-loading-document-state-quickly-and-robustly-for-image-editor).

In what situations will the OS kill the thread and how commonly do these situations occur?

I assume it will be like how Activities are dealt with where the OS can arbitrary decide to kill the thread but will mostly only do this when resources are extremely limited. It would be nice to find some specific documentation of this though.

From playing around, with some test code, a background thread started in onPause() will run indefinitely in the background on my device (I tried loading lots of apps and couldn't get it to be killed).

For my specific app, I'm writing a bitmap editor where I'm using the Command pattern and the Memento pattern to allow undo and redo of edits. I'd like the user to be able to undo/redo their edits even e.g. the user gets a phone call and the activity is killed when it is put in the background. The best solution I can think of is to use a background thread to constantly save my command and memento objects to disk during application use and to finish up saving any objects that are left in a background thread if onPause is called. In the worse case, if the thread is killed I'll only lose some edits.

解决方案

In what situations will the OS kill the thread and how commonly do these situations occur?

The OS will not kill the thread, unless it is killing the process -- Android does not do anything with threads you create yourself. If you are the foreground process, you will not be killed. The odds of Android killing the process within a few seconds of you losing the foreground (after onPause()) are miniscule. The documentation on process lifetime -- what there is of it -- can be found here.