Java Android Asyntask:对上下文使用弱引用以避免设备旋转屏幕
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9809336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android Asyntask: Use weak reference for context to avoid device rotate screen
提问by hqt
In Apress Pro Android 4the 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.
但是作者只是提出了这个建议,并没有说明它是如何完成的。谁做过这个,请举个例子。
采纳答案by kabuko
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
:
在onPostExecute
:
Activity activity = weakActivity.get();
if (activity != null) {
// do your stuff with activity here
}
回答by prijupaul
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
查看此链接了解更多详情
回答by Akhil
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相关的工作。