Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/186.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 活动onPause()时取消异步任务_Android_Android Asynctask_Thread Safety - Fatal编程技术网

Android 活动onPause()时取消异步任务

Android 活动onPause()时取消异步任务,android,android-asynctask,thread-safety,Android,Android Asynctask,Thread Safety,我在活动中启动一个异步任务。。来自服务器的任务请求将检查用户信息是否已验证。此任务将永远运行,除非服务器返回“用户验证”或手动取消 以下是doInBackground代码: @Override protected ApiResult doInBackground(Context... objects) { AccountState accountState = AccountState.getInstance(); ApiResult result

我在活动中启动一个异步任务。。来自服务器的任务请求将检查用户信息是否已验证。此任务将永远运行,除非服务器返回“用户验证”或手动取消

以下是doInBackground代码:

    @Override
    protected ApiResult doInBackground(Context... objects) {
        AccountState accountState = AccountState.getInstance();
        ApiResult result = null;
        boolean isEmailValidated = false;

        while (!isEmailValidated) {
            if (isCancelled()) break;

            result = new MyApi().emailValidated(accountState.getAccessToken());

            if (result != null) {
                MyApi.EmailValidatedResult emailValidatedResult =
                        MyApi.parseEmailValidatedResult(result.getResponse());
                if (emailValidatedResult != null && emailValidatedResult.getValidated()) {
                    isEmailValidated = true;

                } else {
                    // token is not valid, sleep for RETRY_DELAY and try again
                    try {
                        Thread.sleep(RETRY_DELAY);
                    } catch (InterruptedException e) {
                        MyLogger.e(e, "Sleep between retry attempts threw InterruptedException!");
                    }
                }

            } else {
                MyLogger.d("email_validated returned null");
            }
        }
        return result;
    }
由于此任务将保持重试,因此我希望它仅在活动可见时运行。因此,我尝试在活动暂停时取消任务:

@Override
public void onPause() {
    super.onPause();
    if (mCurrentTask != null) {
        mCurrentTask.cancel(true);
        mCurrentTask = null;
    }
}

问题是。。如果在执行Thread.sleep时调用mCurrentTask.cenceltrue。。它将导致中断异常。。我不知道这样行不行。以及如何在不引发异常的情况下很好地处理它。

MayInterruptFrunning参数的全部要点是,它通过引发一个InterruptedException来中断任何I/O操作或等待方法中的任务后台线程,您可以处理该线程以退出它。如果您不希望这样做,那么只需将false传递给cancel方法,而不是true。取消异步任务的示例