gpt4 book ai didi

Android:AsyncTask onPreExecute() 方法未在 UI 线程中执行

转载 作者:太空狗 更新时间:2023-10-29 16:41:56 27 4
gpt4 key购买 nike

我有一个 AsyncTask 从线程执行。在 onPreExecute() 方法中,我想更改一些 TextView,但出现以下错误(回顾):

05-07 11:53:02.039: E/AndroidRuntime(7062): FATAL EXCEPTION: processBarcodeThread
05-07 11:53:02.039: E/AndroidRuntime(7062): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
.....
05-07 11:53:02.039: E/AndroidRuntime(7062): at android.widget.TextView.setText(TextView.java:2573)
05-07 11:53:02.039: E/AndroidRuntime(7062): at it.mbm.droid.activity.fragment.LabelAnagFragment$ReadFromServerTask.onPreExecute(LabelAnagFragment.java:301)
05-07 11:53:02.039: E/AndroidRuntime(7062): at android.os.AsyncTask.execute(AsyncTask.java:391)

这意味着 onPreExecute() 不在 UI 线程上执行,但根据 Android 文档:

onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

那么,我哪里做错了?

最佳答案

您似乎是从后台线程在 AsyncTask 上调用 execute()。如果您阅读了 AsyncTask 的文档,您会发现这是不受支持的:

There are a few threading rules that must be followed for this class to work properly:

  • The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
  • The task instance must be created on the UI thread.
  • execute(Params...) must be invoked on the UI thread. ...

因此,请更改代码以从主应用程序线程调用 AsyncTask 上的 execute()

关于Android:AsyncTask onPreExecute() 方法未在 UI 线程中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16416305/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com