AsyncTask - 为什么我可以在doInBackground方法中访问布局小部件?

时间:2018-03-10 13:33:03

标签: android android-asynctask

根据我的理解,doInBackground方法不应该有权访问布局视图。那么为什么以下代码有效呢?如您所见,我从ProgressBar

访问了doInBackground
private class TestAsyncTask extends AsyncTask<Integer, Integer, String> {
    @Override
    protected String doInBackground(Integer... integers) {
        progressBar.setMax(integers[0]);

        for (int i = 1; i <= integers[0]; i++) {
            try {
                Thread.sleep(1000);
                publishProgress(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return "Finished!";
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
        progressBar.setProgress(0);
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressBar.setProgress(values[0]);
    }
}

1 个答案:

答案 0 :(得分:2)

因为在小部件代码中它检查线程,如果不是UI,它会创建一个Runnable并将其发布到UI线程:

private synchronized void refreshProgress(int id, int progress, boolean fromUser,
            boolean animate) {
        if (mUiThreadId == Thread.currentThread().getId()) {
            doRefreshProgress(id, progress, fromUser, true, animate);
        } else {
            if (mRefreshProgressRunnable == null) {
                mRefreshProgressRunnable = new RefreshProgressRunnable();
            }
            final RefreshData rd = RefreshData.obtain(id, progress, fromUser, animate);
            mRefreshData.add(rd);
            if (mAttached && !mRefreshIsPosted) {
                post(mRefreshProgressRunnable);
                mRefreshIsPosted = true;
            }
        }
    }

RefreshProgressRunnable:使Runnable添加到消息队列中。 runnable将在用户界面线程上运行。