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
}

更多相关文章

  1. 本地方法中printf如何传给java--java系统级命名管道

随机推荐

  1. eventListener将添加到父级,但子元素干扰
  2. AngularJS:如何从外部评估指令?
  3. 如何获取knockoutjs可观察数组的下一个元
  4. ABP(现代ASP.NET样板开发框架)系列之21、
  5. Javascript正则表达式对象和美元符号
  6. javascript-cropper插件翻译笔记
  7. javascript 构造函数中的属性与原型上属
  8. 使用Node.js初始化和配置AWS
  9. 深入浅出 Ajax 读书摘记2——【Ajax请求
  10. Javascript学习:案例7--对象属性和方法的