Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

java - Android Asyntask: Use weak reference for context to avoid device rotate screen

In Apress Pro Android 4 the author has said that:

[...] context of currently running activity will no longer be valid when the device is rotated. [...] One approach is to use a weak reference to the activity instead of a hard reference [...]

But the author just suggest this, and does not tell how it is done. Who has done this before please give me an example.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Somewhere in your AsyncTask you'll want to pass in your activity. Then you'll save that reference in a weak reference. Then you can dereference and use it again in onPostExecute.

Class member:

WeakReference<Activity> weakActivity;

Somewhere in AsyncTask, probably either constructor or onPreExecute:

weakActivity = new WeakReference<Activity>(activity);

In onPostExecute:

Activity activity = weakActivity.get();
if (activity != null) {
   // do your stuff with activity here
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...