Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 287
hqt Avatar asked Mar 21 '12 17:03

hqt


3 Answers

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
}
like image 67
kabuko Avatar answered Nov 14 '22 12:11

kabuko


Here is an example of WeakReference to store a context;

WeakReference<Context> cReference = new WeakReference<Context>(getApplicationContext());

Now we can use this weakReference to do Activity/Context related work.

like image 45
Akhil Avatar answered Nov 14 '22 14:11

Akhil


If you want to restore the previous activity, why not go for onSaveInstanceState and restore it later on.

Check this link for more details

Saving application state

like image 1
prijupaul Avatar answered Nov 14 '22 14:11

prijupaul