javaandroidasynchronousprogressdialogoncreate

Show progress dialog during task without blocking UI thread in Android


@Override
protected void onCreate (Bundle savedInstanceState) {
    
    progressDialog.show();

    if (/* task that returns a boolean value */) {
        // Do stuff        
    }
    else {
        // Do other stuff     
    }

    progressDialog.dismiss();

}

This code should be showing the progress dialog, wait for the task to produce its result, then evaluate the if statement and dismiss the dialog. But this doesn't happen: the UI thread is blocked, the task is executed and only then is the progress dialog shown, only to be dismissed immediately.

What would be the correct way to solve this problem ?


Solution

  • A simple worker thread.

    public void onClick(View v) {
        new Thread(new Runnable() {
            public void run() {
                // a potentially time consuming task
            }
        }).start();
    }
    

    There are other alternatives that can be considered depending on your requirement as mentioned in this answer.