More threads and orientation changes questions
When it comes to threads and orientation changes, it seems the normal thing to do is something like this:
public class Bwent extends Activity {
private static Bwent instance;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
instance = this;
}
//...
That way, if you're making a network request with a thread, and someone changes the orientation of the phone, the thread will know to use the new Activity.
However, is it possible that the thread could finish during the time Android is destroying the old Activity and creating a new one?
Is there a moment in the process where the thread still might be pointing to the wrong Activity, or a partially destroyed activity?
It seems like there shouldn't be, but even usi开发者_高级运维ng a Handler created in the main thread, I'm having intermittent issues with a thread trying to update an object that no longer exists. It's rare, but it does happen.
When it comes to threads and orientation changes, it seems the normal thing to do is something like this:
It is a thing to do. I am not certain whether or not it is the "normal" thing to do. I am dubious that it is the best thing to do.
However, is it possible that the thread could finish during the time Android is destroying the old Activity and creating a new one?
Yes. There is nothing in your code preventing it.
Is there a moment in the process where the thread still might be pointing to the wrong Activity, or a partially destroyed activity?
Yes. There is nothing in your code preventing it.
Instead, try the pattern that I illustrate here. Use an AsyncTask
, implemented as a static inner class or a public class. Have it be the one that knows about the Activity. Have it only use the Activity in doPostExecute()
(or possibly onPublishProgress()
). From the way AsyncTask
and Handler
work, our understanding is that the AsyncTask
will always have an Activity
in those on-the-main-thread methods.
Some of this stuff was discussed recently.
精彩评论