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

早过忘川 提交于 2019-11-28 17:14:33

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
}

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.

prijupaul

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!