使用案例:
用户启动将加载验证码的应用程序。用户填写验证码并尝试下载一些信息。
Problem:
如果用户在下载时旋转设备Activity
被摧毁了。在执行结束时,AsyncTask 尝试更新已销毁的Activity
和result is a “视图未附加到窗口管理器”。
“错误”的解决方案:
我可以用一个来掩盖问题android:configChanges="orientation|keyboardHidden|screenSize"
但这样布局就不会更新为横向。
我要问的是:
是否可以更改方向并更改传递给上下文的“引用”AsyncTask
?
This answer https://stackoverflow.com/questions/2224676/android-view-not-attached-to-window-manager#6240320建议检查对话框是否不为空,但这不是我要找的。
Here https://stackoverflow.com/questions/1111980/how-to-handle-screen-orientation-change-when-progress-dialog-and-background-thre#4481297他建议使用 WeakReference (here https://stackoverflow.com/questions/4220625/android-context-leaks-in-asynctask#4220746关于如何使用它的一个很好的片段)但我不明白这是否是我正在寻找的。
更明确地说,这就是我在 onPostExecute 中所做的事情:
@Override
protected void onPostExecute(Auto result) {
progress.dismiss();
new DownloaderCaptcha(context).execute("");
((EditText)context.findViewById(R.id.editTextCaptcha)).setText("");
context.findViewById(R.id.progrBar).setVisibility(View.VISIBLE);
context.findViewById(R.id.captcha).setVisibility(View.INVISIBLE);
if(result != null) {
Storage.storeHistory(context, result.getTarga().getValue());
Intent i = new Intent(context, MenuActivity.class);
i.putExtra("result", result);
context.startActivity(i);
} else {
ErrorDialog.show(context, error);
}
}