gpt4 book ai didi

java - Android Asynctask : Use weak reference for context to avoid device rotate screen

转载 作者:IT老高 更新时间:2023-10-28 21:04:36 27 4
gpt4 key购买 nike

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

但作者只是建议这样做,并没有说明它是如何完成的。有谁做过,请举个例子。

最佳答案

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

类(class)成员:

WeakReference<Activity> weakActivity;

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

weakActivity = new WeakReference<Activity>(activity);

onPostExecute中:

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

关于java - Android Asynctask : Use weak reference for context to avoid device rotate screen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9809336/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com