简体   繁体   中英

Display loading dialog while running method in Android?

I have a method setup that takes about 3-5 seconds to run (because it does something online) and I would like to show a loading dialog, but I cant figure out how to do it, I tried starting the loading dialod before I called the method then tried to dismiss it right after like this:

dialog.show();
myMethod();
dialog.cancel();

But that didn't work, does anyone have any suggestions?

AsyncTask is my Favouite but you may use Handlers too :)

Invest your time to go through this nice blog .

Below snippet will help you.

    package org.sample;

    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.os.Bundle;
    import android.os.Handler;

    public class Hello extends Activity {

        private Handler handler;
        private ProgressDialog dialog;

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

            dialog = new ProgressDialog(this);
            dialog.setMessage("Please Wait!!");
            dialog.setCancelable(false);
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.show();

            new Thread() {
                public void run() {
                    // Do operation here.
                    // ...
                    // ...
                    // and then mark handler to notify to main thread 
                    // to  remove  progressbar
                    //
                    // handler.sendEmptyMessage(0);
                    //
                    // Or if you want to access UI elements here then
                    //
                    // runOnUiThread(new Runnable() {
                    //
                    //     public void run() {
                    //         Now here you can interact 
                    //         with ui elemements.
                    //
                    //     }
                    // });
                }
            }.start();

            handler = new Handler() {
                public void handleMessage(android.os.Message msg) {
                    dialog.dismiss();
                };
            };
        }
    }

Running a long duration task on the UI thread is a "no no". Use AsyncTask to run the long duration tasks in the background and update the UI when it is complete.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM