35

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.

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
hqt
  • 28,467
  • 48
  • 168
  • 241

3 Answers3

89

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
}
kabuko
  • 35,577
  • 9
  • 76
  • 92
  • 2
    `activity` will still be invalid reference if GC didn't kick in time. Please correct me if I am wrong. – q126y Jun 30 '16 at 15:41
  • 1
    does this avoid memory leak? – Mahdi-Malv Mar 17 '18 at 19:31
  • The in the object definition is not required if language level is set to Java 8 – Peter Chaula Jul 23 '18 at 14:20
  • `WeakReference` has a property called `isEnqueued` (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 – Leo Aug 17 '19 at 04:08
4

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.

Akhil
  • 13,450
  • 7
  • 32
  • 39
  • 4
    Storing the Application Context in a WeakReference is pretty pointless. The Application Context lives as long as the application does and will never get dereferenced. – JensV Mar 18 '19 at 09:11
1

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

Community
  • 1
  • 1
prijupaul
  • 2,056
  • 1
  • 15
  • 17