如何处理后台线程

如何处理后台线程

本文介绍了离开 Activity 时,Android 如何处理后台线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要我的 Android 应用在其活动被置于后台或被终止时将其状态保存到磁盘.有人建议我在调用 onPause() 时启动一个线程并在那里执行任何昂贵的 I/O 过程(参见 为图像编辑器快速而稳健地保存/加载文档状态).

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 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.

通过一些测试代码,在 onPause() 中启动的后台线程将在我设备的后台无限期运行(我尝试加载大量应用程序,但无法将其杀死).

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).

对于我的特定应用程序,我正在编写一个位图编辑器,我在其中使用命令模式和备忘录模式来允许撤消和重做编辑.我希望用户能够撤消/重做他们的编辑,例如用户接到一个电话,活动被置于后台时被终止.我能想到的最佳解决方案是使用后台线程在应用程序使用期间不断将我的命令和备忘录对象保存到磁盘,并在调用 onPause 时完成保存留在后台线程中的任何对象.在更糟糕的情况下,如果线程被杀死,我只会丢失一些编辑.

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.

推荐答案

操作系统不会终止线程,除非它终止进程——Android 不会对您自己创建的线程执行任何操作.如果你是前台进程,你不会被杀死.Android 在您失去前台后(在 onPause() 之后)几秒钟内终止进程的可能性微乎其微.可以在 这里.

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.

这篇关于离开 Activity 时,Android 如何处理后台线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:17