异步任务无法访问原始线程

时间:2018-11-09 06:47:20

标签: java android android-asynctask

我已将代码移至异步任务以在后台线程上执行操作。代码如下:

public class AsynTaskActivity  extends  AsyncTask<HashMap<String, Integer>, Void, Void>
{

    @Override
    protected Void doInBackground(HashMap<String, Integer>... hashMaps)
    {

        HashMap<String, Integer> maps = hashMaps[0];
        //
        Set set = maps.entrySet();
        for (Object aSet : set)
        {
            Map.Entry entry = (Map.Entry) aSet;

            receiveBarcode(entry.getKey().toString());
        }
        return null;
    }
}

但是,在运行代码库时。我遇到以下错误:

Process: com.touchsides.checkout.debug, PID: 7447
java.lang.RuntimeException: An error occurred while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:309)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
    at java.lang.Thread.run(Thread.java:818)
 Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
    at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6556)
    at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:942)

我假定doInbackground在单独的线程上运行,并且不应遇到此错误。

3 个答案:

答案 0 :(得分:2)

在引用某项活动时使用runOnUiThread()

答案 1 :(得分:2)

AsyncTask中,您永远无法在doInBackgound中执行UI交互,但是,如果您分别在onProgressUpdateonPostExecute中传递进度或结果,则仍然可以更新UI,这就是您重新获得UI线程的方式。您可以尝试将AsyncTask更改为以下内容:

public class AsynTaskActivity extends AsyncTask<HashMap<String, Integer>, String, Object> {

    @Override
    protected Object doInBackground(HashMap<String, Integer>... hashMaps) {
        // non-ui thread
        HashMap<String, Integer> maps = hashMaps[0];
        Set set = maps.entrySet();
        for (Object aSet : set) {
            Map.Entry entry = (Map.Entry) aSet;
            publishProgress(entry.getKey().toString()); // onProgressUpdate callback
        }
        return null; // onPostExecute callback
    }

    @Override
    protected void onProgressUpdate(String... progress) {
        // ui thread
        receiveBarcode(progress);
    }

    @Override
    protected void onPostExecute(Long result) {
        // ui thread
    }
}

AsyncTask有据可查,您可以在线阅读有关此内容的更多信息。

答案 2 :(得分:0)

在您的onPostExecute()中覆盖AsyncTask方法,然后在其中进行用户界面操作。

如果您真的想用doInBackground()方法更改UI,则可以使用Handler来完成。