【发布时间】:2016-11-18 10:28:04
【问题描述】:
我已经声明了一个在后台工作的类:
public class ReportLoadTask extends AsyncTask<Void,Void, ReportLoadTaskResult> {
public ReportLoadTask(Context context, String barcode, ReportLoadTaskListener l) {
...
}
}
我使用这个类的一个实例作为Activity的局部变量:
private ReportLoadTask mReportLoadTask;
...
在课堂的一个点的代码中,我正在准备一项任务,然后让用户通过显示AlertDialog 来决定是否继续:
mReportLoadTask = new ReportLoadTask(this, barcode, this)
...
new AlertDialog.Builder(this)
.setMessage("Continue with search?" )
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mReportLoadTask.execute();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mReportLoadTask = null;
return;
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
测试时,如果我在显示AlertDialog 时销毁Activity(例如通过旋转设备),我期望mReportLoadTask 变为null。但在实践中,这不会发生。所有Activity 生命周期方法(OnPause、OnStop、OnDestroy)都被正确调用,甚至其他局部变量(一些ints)都被破坏了,但这个变量似乎以某种方式“存活”。这是为什么呢?
在探索了网络之后,Android 似乎在某处保留了该对象的引用,但它可以将它保留在哪里?这个对象的唯一引用是在我的Activity 中,它正在被销毁。
【问题讨论】:
-
可能
mReportLoadTask正在运行,在使mReportLoadTask对象为null 之前调用mReportLoadTask.cancel后是否尝试过? -
mReportLoadTask只有在明确设置null时才会变为null
标签: android android-asynctask ondestroy