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

Mr Heelis :

I recently re-imported a perfectly fine android project into Android Studio and it has unilaterally decided to complain (and red under squiggle) code that is DEFINITELY safe.

I get this red squiggle in the IDE every time (but only in 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();
}

What is the cause and why does the code run perfectly fine anyway?

IDE screenshot. Red squiggle underneath publishProgress method

Michael Dodd :

This is a linting issue. From the documentation for publishProgress(Params...) (my bold):

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

So this method is designed to only be called on a background thread, and this is reflected in the source of the method with the @WorkerThread annotation:

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

So while doInBackground(String...) is run on a background thread, onPostExecute(String checkPhpResponse) is run on the UI thread as you're meant to update your UI directly within that callback. Because publishProgress(Params...) is annotated as @WorkerThread, the IDE throws up an error even though the code will compile - it works, but it's bad practice.

Without any further context as to how your AsyncTask is being used I can't advise as to how to update your code, but I would advise to avoid using publishProgress(boolean) and instead update your UI directly from within onPostExecute(String)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=132430&siteId=1