Android Asyntask:对上下文使用弱引用以避免设备旋转屏幕

时间:2022-01-06 14:21:41

In Apress Pro Android 4 the author has said that:

在Apress Pro Android 4中,作者说过:

[...] 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.

但作者只是建议这一点,并没有告诉它是如何完成的。谁曾经这样做过请给我一个例子。

3 个解决方案

#1


68  

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.

在您的AsyncTask中的某个地方,您需要传递您的活动。然后,您将在弱引用中保存该引用。然后你可以在onPostExecute中取消引用并再次使用它。

Class member:

WeakReference<Activity> weakActivity;

Somewhere in AsyncTask, probably either constructor or onPreExecute:

在AsyncTask中的某个地方,可能是构造函数或onPreExecute:

weakActivity = new WeakReference<Activity>(activity);

In onPostExecute:

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

#2


2  

Here is an example of WeakReference to store a context;

以下是存储上下文的WeakReference示例;

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

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

现在我们可以使用这个weakReference来做与Activity / Context相关的工作。

#3


0  

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

如果要恢复以前的活动,为什么不去onSaveInstanceState并稍后恢复它。

Check this link for more details

查看此链接了解更多详情

Saving application state

保存应用程序状态

#1


68  

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.

在您的AsyncTask中的某个地方,您需要传递您的活动。然后,您将在弱引用中保存该引用。然后你可以在onPostExecute中取消引用并再次使用它。

Class member:

WeakReference<Activity> weakActivity;

Somewhere in AsyncTask, probably either constructor or onPreExecute:

在AsyncTask中的某个地方,可能是构造函数或onPreExecute:

weakActivity = new WeakReference<Activity>(activity);

In onPostExecute:

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

#2


2  

Here is an example of WeakReference to store a context;

以下是存储上下文的WeakReference示例;

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

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

现在我们可以使用这个weakReference来做与Activity / Context相关的工作。

#3


0  

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

如果要恢复以前的活动,为什么不去onSaveInstanceState并稍后恢复它。

Check this link for more details

查看此链接了解更多详情

Saving application state

保存应用程序状态