Android Asyntask: Use weak reference for context to avoid device rotate screen
Solution 1
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
}
Solution 2
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.
Solution 3
If you want to restore the previous activity, why not go for onSaveInstanceState and restore it later on.
Check this link for more details
hqt
Those who don't speak math are doomed to speak nonsense. My brief profile: https://github.com/hqt/profile
Updated on June 08, 2020Comments
-
hqt almost 4 years
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.
-
q126y almost 8 years
activity
will still be invalid reference if GC didn't kick in time. Please correct me if I am wrong. -
Mahdi-Malv about 6 yearsdoes this avoid memory leak?
-
Peter Chaula almost 6 yearsThe <Activity> in the object definition is not required if language level is set to Java 8
-
JensV about 5 yearsStoring the Application Context in a WeakReference is pretty pointless. The Application Context lives as long as the application does and will never get dereferenced.
-
Leo over 4 years
WeakReference
has a property calledisEnqueued
(I think) that you can use to determine if the referenced object is enquequed for garbage collection. If it is, then you can assume that object is no longer valid