Android Asyntask:对上下文使用弱引用以避免设备旋转屏幕
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
}