Change a dialog's message while using AsyncTask?

前端 未结 2 375
你的背包
你的背包 2020-12-22 05:51

I looked at a few other questions regarding a similar issue, and I figured out that I need to use the onProgressUpdate method to change the message of Pro

相关标签:
2条回答
  • 2020-12-22 06:29

    You need to implement the onProgressUpdate method of AsyncTask. Create a new class that holds the progress percentage and the message only to be the onProgressUpdate method's only parameter.

    In the onProgressUpdate, call dia.setProgress and dia.setMessage.

    In your doInBackground method, call publishProgress with an instance of your new class that contains the new percentage and message. That will cause the AsyncTask to call onProgressUpdate on the main thread.

    For example:

    private static class TaskProgress {
        final int percentage;
        final String message;
    
        TaskProgress(int percentage, String message) {
            this.percentage = percentage;
            this.message = message;
        }
    }
    

    In your AsyncTask (replace the ?s with the correct types for your implementation):

    public ProgressAsyncTask extends AsyncTask<?, TaskProgress, ?> {
    
        public void onProgressUpdate(TaskProgress progress) {
             pictures.dia.setProgress(progress.percentage);
             pictures.dia.setMessage(progress.message);
        }
    
        public ? doInBackground(?... params) {
            // ... your code       
            publishProgress(new TaskProgress(30, "A new update"));
            // ... your code 
        }
    
    }
    
    0 讨论(0)
  • 2020-12-22 06:32

    You're right in that you should put the code for updating the views in dia in the onProgressUpdate method. To ensure that onProgressUpdate is called, though, you need to make calls to publishProgress. Basically, you call publishProgress from your background thread and then the system, at some undefined time in the future, will invoke onProgressUpdate on the UI thread.

    0 讨论(0)
提交回复
热议问题