方法publishProgress必须从工作线程调用,目前推断线程为主线程

Method publishProgress must be called from the worker thread, currently inferred thread is main thread

我最近将一个非常好的 android 项目重新导入到 Android Studio 中,它单方面决定抱怨(并且在波浪线下显示为红色)绝对安全的代码。

我每次都在 IDE 中看到这个红色波浪线(但只在 postExecute 中):

Method publishProgress must be called from the worker thread, currently inferred thread is main thread

private void triggerClick() { 

    final class LoginHttpTask
            extends
            AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {

        @Override
        protected String doInBackground(String... params) {
            publishProgress(true);
         }

        @Override
        protected void onPostExecute(String checkPhpResponse) {
            publishProgress(false);
        }   

   } 
   new LoginHttpTask.execute();
}

原因是什么?为什么代码 运行 完全没问题?

这是一个 linting 问题。来自 publishProgress(Params...)(我的粗体)的文档:

This method can be invoked from doInBackground(Params...) to publish updates on the UI thread while the background computation is still running.

所以这个方法被设计为只能在后台线程上调用,这反映在方法的 in the source@WorkerThread 注解:

@WorkerThread
protected final void publishProgress(Progress... values) {
    if (!isCancelled()) {
        getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
                new AsyncTaskResult<Progress>(this, values)).sendToTarget();
    }
}

因此,虽然 doInBackground(String...) 在后台线程上 运行,但 onPostExecute(String checkPhpResponse) 在 UI 线程上 运行,因为您打算更新您的UI 直接在该回调中。因为 publishProgress(Params...) 被注释为 @WorkerThread,即使代码可以编译,IDE 也会抛出错误 - 它有效,但这是不好的做法。

没有任何关于如何使用您的 AsyncTask 的进一步上下文,我无法建议如何更新您的代码,但我建议避免使用 publishProgress(boolean) 而是更新您的UI 直接来自 onPostExecute(String)