Android ProgressDialog with threading issues

I have encountered a problem using ProgressDialog while running a process. I have tried all the incorrect methods, checked many websites, and provided examples I want to do. However, I still encounter the problem that threads run before ProgressDialog appears. This is my recent attempt:

new Thread(new Runnable() {
     public void run() {
        dialog = new ProgressDialog(EPD.this);
        dialog.setMessage("Loading. Please Wait...");
        dialog.show();         
                    }
 }).run();
 getMostWanted();                       

In addition to trying this way, I also tried to use the new thread in getmostwanted(), but I still have the same result. It pauses for about 4 or 5 seconds when getmostwanted() and there is no dialog box

Thank you for your help

resolvent:

If you are on the main thread, you should use it to display ProgressDialog and separate another thread for getmostwanted(). Suppose you want the end of getmostwanted() to close the dialog, you should look at asynctask:

private class GetMostWanted extends AsyncTask<Void, Void, Void> {
     private final ProgressDialog dialog;

     public GetMostWanted() {
          dialog = new ProgressDialog(EPD.this);
          dialog.setMessage("Loading. Please Wait...");
     }

     protected void onPreExecute() {
         dialog.show();
     }

     protected void doInBackground(Void... unused) {
         getMostWanted();
     }

     protected void onPostExecute(Void unused) {
         dialog.dismiss();
     }
 }

In this way, your processing is executed on the background thread in doinbackground (), and then you can close the dialog on the main thread in onpostexecute ()

Now you can use:

new GetMostWanted(dialog).execute();

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>