开发者

Are progress/indeterminate dialog boxes added to the end of the UI thread? Do they require a second thread?

I have a simple dialog box. When I click a button the dialog box is supposed to be shown, while a file save operation is performed, and then the dialog box is dismissed. The problem I am having is the dialog box isn't shown until after the onClick event of the button finishes.

Taken from the Dialog developer doc:

The setup is simple. Most of the code needed to create a progress dialog is actually involved in the process that updates it. You might find that it's necessary to create a second thread in your application for this work and then report the progress back to the Activity's UI thread with a Handler object. If you're not familiar with using additional threads with a Handler, see the example Activity below that uses a second thread to increment a progress dialog managed by the Activity.

Why isn't the dialog shown until after the onClick method finishes? Is the dialog added to the end of the UI thread?

Is the only way to do this to create a new thread and handler? That's fairly bad wording in the developer doc if so.

Thanks all.

    Button send = (Button) findViewById(R.id.send);
    send.setOnClickListener(new OnClickListener() {         
        @Override
        public void onClick(View v) {
            showDialog(SAVING_DIALOG);              
            //Do all the file saving operations
            ...
            ...
            dismissDialog开发者_如何学Go(SAVING_DIALOG);
        }
    });

Here is the dialog

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case SAVING_DIALOG: {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setMessage("Saving file...");
            dialog.setIndeterminate(true);
            dialog.setCancelable(false);
            return dialog;
        }
    }
    return null;
}


Shouldn't work be done on a thread when using the progress dialog?

http://www.helloandroid.com/tutorials/using-threads-and-progressdialog


For showing a progress dialog while something is processing, you have to process your code in another thread, otherwise your dialog freezes or wont be shown.

So I would use following method:

final Handler threadHandler = new Handler();

// in your onClick:
showDialog(SAVING_DIALOG);
new Thread(){
    public void run(){
        // new thread
        // Do all the file saving operations
        // ...
        threadHandler.post(new Runnable(){public void run(){
            // back in UI thread
            dismissDialog(SAVING_DIALOG);
        }});
    }
}.start();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜