I have an activity that may have threads running when the user presses back and 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();
That is 8 threads to everything the phone does--all android features, texting, memory management, Java, and any other apps that are running. You say it is limited to 128, but realistically it is limited functionally to much less for you to use than that.
Since all fragments are destroyed if the activity is destroyed, a simple answer could be calling getActivity(). isDestroyed() returning true if the activity is destroyed, therefore the fragment is destroyed.
Android has four basic types of threads. You'll see other documentation talk about even more, but we're going to focus on Thread , Handler , AsyncTask , and something called HandlerThread . You may have heard HandlerThread just called the “Handler/Looper combo”.
When an application is launched in Android, it creates the primary thread of execution, referred to as the “main” thread. Most thread is liable for dispatching events to the acceptable interface widgets also as communicating with components from the Android UI toolkit.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With