How does Android handle background threads when leaving an Activity?

后端 未结 3 1897
感情败类
感情败类 2020-12-16 10:02

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 a

3条回答
  •  长情又很酷
    2020-12-16 10:15

    Normally, saving your state in onPause is the right thing to do if it's quick. I don't think it's clearly documented when a process is killed, but you sometimes see it in logcat when you run some demanding apps (say, after running Google Earth and Browser).

    There's also an option in the Android DevTools to automatically destroy activities as you navigate away from them, although that probably doesn't extend to the process. (DevTools are on the emulator, and on some rooted phones).

    I think your approach sound reasonable - use a low-priority thread to constantly update the save data, and give it normal priority in onPause, and set a flag in onPause that tells it to terminate after it finishes.

    Obviously, you'll need to make sure you don't run into synchronization issues if you get to onResume immediately after onPause (i.e. while the thread is still busy saving).

提交回复
热议问题