且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android AsyncTasks如何检查活动是否仍在运行

更新时间:2023-12-05 09:22:34

您可以在活动的onDestroy中取消异步任务

You can cancel your asynctask in the activity's onDestroy

@Override
protected void onDestroy() {
    asynctask.cancel(true);
    super.onDestroy();
}

并在执行更改时检查您的异步任务是否已取消(活动被破坏)

and when performing changes you check whether your asynctask has been cancelled(activity destroyed) or not

protected void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);
    if(!isCancelled()) {
         gender.setText(values[0]);
    }
}