使用FLAG_ACTIVITY_CLEAR_TOP启动活动

时间:2016-05-31 14:12:10

标签: android android-intent android-asynctask

使用AsyncTask从使用AsyncTask执行某些重要后台工作的活动中使用Flag FLAG_ACTIVITY_CLEAR_TOP启动活动时。后台任务会发生什么?

1 个答案:

答案 0 :(得分:2)

后台任务将继续处理。

来自docs:

  

如果已设置,并且正在启动的活动已在当前任务中运行,则不会启动该活动的新实例,而是将关闭其上的所有其他活动,并将此Intent传递给(现在在最前面)作为新意图的旧活动。

如何运作AsyncTask? 我们来看看AsyncTask来源:

/**
     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     */
    public AsyncTask() {
        mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);

                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //noinspection unchecked
                Result result = doInBackground(mParams);
                Binder.flushPendingCommands();
                return postResult(result);
            }
        };

        mFuture = new FutureTask<Result>(mWorker) {
            @Override
            protected void done() {
                try {
                    postResultIfNotInvoked(get());
                } catch (InterruptedException e) {
                    android.util.Log.w(LOG_TAG, e);
                } catch (ExecutionException e) {
                    throw new RuntimeException("An error occurred while executing doInBackground()",
                            e.getCause());
                } catch (CancellationException e) {
                    postResultIfNotInvoked(null);
                }
            }
        };
    }

我们只需要记住两件事。

  • WorkerRunnable实际上是Callable
  • 结果result = doInBackground(mParams); //在后台线程中处理

所以这是你的答案。将处理doInBackground,但可能会生成onPostExecute NPE,因为父活动已被销毁。

相关问题