Activity 的局部变量在 OnDestroy() 之后仍然有效

Activity's local variable still valid after OnDestroy()

我已声明 class 用于后台工作:

public class ReportLoadTask extends AsyncTask<Void,Void, ReportLoadTaskResult> {

    public ReportLoadTask(Context context, String barcode, ReportLoadTaskListener l) {
        ...
    }

}

我正在使用此 class 的实例作为 Activity 的局部变量:

private ReportLoadTask mReportLoadTask;

...

在 class' 代码的一点中,我正在准备一项任务,然后通过显示 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 生命周期方法(OnPauseOnStopOnDestroy)都被正确调用,甚至其他局部变量(一些 ints)也被破坏了,但这变量似乎 "survive"。这是为什么?

在浏览网络后,似乎 Android 正在某处保留此对象的引用,但它可以保留在哪里?对该对象的唯一引用在我的 Activity 中,它正在被销毁。

如果您在显示对话框时旋转设备,则表示您的任务未执行(您尚未调用 execute)。当你旋转设备时,你的activity被销毁并重新创建(它将从头开始并且生命周期回调将再次被调用).

当 activity 被重新创建时 mReportLoadTask = new ReportLoadTask(this, barcode, this) 被再次调用并且你得到一个 new instance.