ProgressDialog in a separate thread

旧巷老猫 提交于 2019-12-04 20:16:08
kvh

1.show your process dialog in main thread

2.start a new thread (such as Thread A) to process your heavy job

3.when done, use handler to send a message from Thread A to main thread, the latter dismisses the process dialog

code like this private ProcessDialog pd;

private void startDialog()
{

 pd = ProgressDialog.show(MainActivity.this, "title", "loading");  

     //start a new thread to process job
     new Thread(new Runnable() {  
         @Override  
         public void run() {  
             //heavy job here
             //send message to main thread
             handler.sendEmptyMessage(0); 
          }  
      }).start(); 
}

Handler handler = new Handler() {  
    @Override  
    public void handleMessage(Message msg) {
        pd.dismiss(); 
    }  
};

Try something like this:

private class MyAwesomeAsyncTask extends AsyncTask<Void, Void, Void> {

    private ProgressDialog mProgress;

    @Override
    protected void onPreExecute() {
        //Create progress dialog here and show it
    }

    @Override
    protected Void doInBackground(Void... params) {

        // Execute query here

        return null;

    }  

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        //update your listView adapter here
        //Dismiss your dialog

    }

}

To call it:

new MyAwesomeAsyncTask().execute(); 
Daniele Testa

All you need to do, is to tell Android to run it on the main UI thread. No need to create a Handler.

runOnUiThread(new Runnable() {
    public void run() {
        progressDialog.dismiss();
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!