安卓Asyntask:使用的情况下,以避免设备旋转屏幕弱引用 [英] Android Asyntask: Use weak reference for context to avoid device rotate screen

查看:134
本文介绍了安卓Asyntask:使用的情况下,以避免设备旋转屏幕弱引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个preSS专业版的Andr​​oid 4.0 的笔者曾经说过,:

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.

推荐答案

放在你的的AsyncTask 你要通过你的活动。然后,你可以节省在弱引用的参考。然后你就可以提领,又在 onPostExecute 使用它。

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.

类成员:

WeakReference<Activity> weakActivity;

在某处的AsyncTask ,大概无论是构造或在preExecute

Somewhere in AsyncTask, probably either constructor or onPreExecute:

weakActivity = new WeakReference<Activity>(activity);

onPostExecute

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

这篇关于安卓Asyntask:使用的情况下,以避免设备旋转屏幕弱引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆