What happens to an activity's threads and views when it's destroyed?
I have an activity that may have threads running when the user presses back an开发者_运维技巧d finish()es the activity. What happens to those threads at that point? Will they all attempt to complete unless I interrupt them in onDestroy()?
For example, is the below code unsafe, because my views and cursor may be destroyed if the activity finishes before the thread?
The reason I ask is that I have occasional crashes when finishing activities that I haven't successfully debugged yet, because they happen rarely and never while I've been in debug mode. I have since started checking if my view objects are null before doing anything to them in runOnUIThread(). Not sure if that's the cleanest solution, or if that is the problem at all.
new Thread()(
public void run(){
crunchOnSomethingForAwhile(mCursor);
MyActivity.this.runOnUIThread(new Runnable(){
public void run(){
mTextView.setText("thread complete");
mCursor.close();
}
}
}
).start();
I would look at using AsyncTask instead of a simple Thread
. It has some built in support for doing work in another thread, and then upon finish doing something on the UI thread.
That said, there are a number of threads around that talk about how to deal with AsyncTask
s when the activity ends. What exactly you should do depends on what the task is doing. If it is only applicable to that Activity, then you can just cancel the task in onPause (assuming it is not just a rotation change).
Otherwise, there are various tactics for holding on to the AsyncTasks across Activities. See this question for some ideas. This commonsware blog also has an example of holding onto an AsyncTask across a screen rotation.
Someone posted an answer on another thread that onDestroy sets all view references to null, and finally the activity reference to null. So I will assume that it is best practice to interrupt all running threads in onDestroy, or at least catch NullPointerExceptions in any runInUIThread methods.
精彩评论