Android ProgressDialog 不工作

Android ProgressDialog isn't working

我尝试制作一个 ProgressDialog,向用户显示与蓝牙设备连接的进度,但我的进度对话框停留在 0%,并且蓝牙设备未连接。当我调用 onCreate() 中的函数时,它会连接,但是当我这样做时我不会有 ProgressDialog。

我不知道该怎么办!

请帮忙!

这是我的代码

public void StartConnection(){
    loading = new ProgressDialog(this);
    loading.setTitle("Loading connection...");
    loading.setMessage("Loading...");
    loading.setProgressStyle(loading.STYLE_HORIZONTAL);
    loading.setProgress(0);
    loading.setMax(100);
    loading.show();

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                //Get device ID
                loading.setProgress(0);
                loading.setMessage("Getting device ID...");
                try {
                    getDeviceId();
                } catch (Exception ex) {
                    ErrorMessage("Couldn't get device ID");
                    ErrorAlert += "Error 101: Couldn't get device ID\n";
                }
                Thread.sleep(2000);
                loading.setProgress(20);

                //Open connection
                loading.setMessage("Opening connection...");
                try{
                    openConnection();
                } catch (IOException ex){
                    ErrorMessage("Couldn't open connection");
                    ErrorAlert += "Error 102: Couldn't open connection\n";
                }
                Thread.sleep(2000);
                loading.setProgress(40);

                //Testing connection
                loading.setMessage("Testing connection...");
                if (!mmSocket.isConnected()){
                    ErrorMessage("Test failed!");
                    ErrorAlert += "Error 103: Test failed!\n";
                }
                Thread.sleep(2000);
                loading.setProgress(60);

                //Calibrate sensors
                loading.setMessage("Calibrating sensors...");
                try{
                    sendCommand("c");
                }catch (IOException ex){
                    ErrorMessage("Couldn't calibrate sensors");
                    ErrorAlert += "Error 104: Couldn't calibrate sensors\n";
                }
                Thread.sleep(2000);
                loading.setProgress(80);

                //Finish
                loading.setMessage("Finishing...");
                Thread.sleep(1000);
                loading.setProgress(90);

                //Clear
                loading.setMessage("Clearing some stuff...");
                Thread.sleep(1000);
                loading.setProgress(100);

                if (loading.getProgress() == loading.getMax()) {
                    loading.dismiss();
                    Toast.makeText(getApplicationContext(), "Finished, connection is established", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {

            }
        }
    }).start();

}

编辑: 我认为这是问题所在:

03-05 19:34:28.342 3488-3488/com.jules_citronic.racecarcontrol E/ActivityThread: Performing stop of activity that is not resumed: {com.jules_citronic.racecarcontrol/com.jules_citronic.racecarcontrol.Menu}
                                                                             java.lang.RuntimeException: Performing stop of activity that is not resumed: {com.jules_citronic.racecarcontrol/com.jules_citronic.racecarcontrol.Menu}
                                                                                 at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3509)
                                                                                 at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3594)
                                                                                 at android.app.ActivityThread.-wrap20(ActivityThread.java)
                                                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1392)
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                 at android.os.Looper.loop(Looper.java:148)
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:5466)
                                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

编辑: 我尝试应用您的建议,但出现此错误:

AndroidStudio gives an error

编辑: 呃,还是不行:(

First

这是整个函数:

private void StartConnection(){
    loading = new ProgressDialog(this);
    loading.setTitle("Loading connection...");
    loading.setMessage("Loading...");
    loading.setProgressStyle(loading.STYLE_HORIZONTAL);
    loading.setProgress(0);
    loading.setMax(100);
    loading.show();

    new Thread( runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                //Get device ID
                loading.setProgress(0);
                loading.setMessage("Getting device ID...");
                try {
                    getDeviceId();
                } catch (Exception ex) {
                    ErrorMessage("Couldn't get device ID");
                    ErrorAlert += "Error 101: Couldn't get device ID\n";
                }
                Thread.sleep(2000);
                loading.setProgress(20);

                //Open connection
                loading.setMessage("Opening connection...");
                try {
                    openConnection();
                } catch (IOException ex) {
                    ErrorMessage("Couldn't open connection");
                    ErrorAlert += "Error 102: Couldn't open connection\n";
                }
                Thread.sleep(2000);
                loading.setProgress(40);

                //Testing connection
                loading.setMessage("Testing connection...");
                if (!mmSocket.isConnected()) {
                    ErrorMessage("Test failed!");
                    ErrorAlert += "Error 103: Test failed!\n";
                }
                Thread.sleep(2000);
                loading.setProgress(60);

                //Calibrate sensors
                loading.setMessage("Calibrating sensors...");
                try {
                    sendCommand("c");
                } catch (IOException ex) {
                    ErrorMessage("Couldn't calibrate sensors");
                    ErrorAlert += "Error 104: Couldn't calibrate sensors\n";
                }
                Thread.sleep(2000);
                loading.setProgress(80);

                //Finish
                loading.setMessage("Finishing...");
                Thread.sleep(1000);
                loading.setProgress(90);

                //Clear
                loading.setMessage("Clearing some stuff...");
                Thread.sleep(1000);
                loading.setProgress(100);

                if (loading.getProgress() == loading.getMax()) {
                    loading.dismiss();
                    Toast.makeText(getApplicationContext(), "Finished, connection is established", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {

            }
        }
    })).start();
}

编辑: 修复了 runOnUiThread:

private void StartConnection(){
    loading = new ProgressDialog(this);
    loading.setTitle("Loading connection...");
    loading.setMessage("Loading...");
    loading.setProgressStyle(loading.STYLE_HORIZONTAL);
    loading.setProgress(0);
    loading.setMax(100);
    loading.show();

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                //Get device ID
                loading.setProgress(0);
                loading.setMessage("Getting device ID...");
                try {
                    getDeviceId();
                } catch (Exception ex) {
                    ErrorMessage("Couldn't get device ID");
                    ErrorAlert += "Error 101: Couldn't get device ID\n";
                }
                Thread.sleep(2000);
                loading.setProgress(20);

                //Open connection
                loading.setMessage("Opening connection...");
                try {
                    openConnection();
                } catch (IOException ex) {
                    ErrorMessage("Couldn't open connection");
                    ErrorAlert += "Error 102: Couldn't open connection\n";
                }
                Thread.sleep(2000);
                loading.setProgress(40);

                //Testing connection
                loading.setMessage("Testing connection...");
                if (!mmSocket.isConnected()) {
                    ErrorMessage("Test failed!");
                    ErrorAlert += "Error 103: Test failed!\n";
                }
                Thread.sleep(2000);
                loading.setProgress(60);

                //Calibrate sensors
                loading.setMessage("Calibrating sensors...");
                try {
                    sendCommand("c");
                } catch (IOException ex) {
                    ErrorMessage("Couldn't calibrate sensors");
                    ErrorAlert += "Error 104: Couldn't calibrate sensors\n";
                }
                Thread.sleep(2000);
                loading.setProgress(80);

                //Finish
                loading.setMessage("Finishing...");
                Thread.sleep(1000);
                loading.setProgress(90);

                //Clear
                loading.setMessage("Clearing some stuff...");
                Thread.sleep(1000);
                loading.setProgress(100);

                if (loading.getProgress() == loading.getMax()) {
                    loading.dismiss();
                    Toast.makeText(getApplicationContext(), "Finished, connection is established", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {

            }
        }
    });
}

但现在 ProgressDialog 根本没有出现。:( 当我单击启动 activity 的按钮时,屏幕变黑并冻结,当蓝牙连接时,它会加载布局。从未显示 ProgressDialog。

我认为您希望从新线程更新 ProgressDialog,但它是在 UI 线程上创建的。你不能那样做。查看 IDE 的输出日志。 看看这个 link 添加 runOnUiThread 方法。

它适用于 OnCreate,因为代码由 UI 线程执行。

Android 本身包含一个很好的 API 用于需要与主 UI 线程交互的后台进程。AsyncTask 是实现这一点的方法,它将为您省去所有繁重的工作,使所有线程操作对您来说都非常容易(内部使用 ThreadHandlerExecutorThreadPoolExecutorFutureTask 等) .

勾选 this example,您只需几步就能让它发挥作用。

您只需要了解 AsyncTask 助手的主要概念:

When an asynchronous task is executed, the task goes through 4 steps:

1 - onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

2 - doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

3 - onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

4 - onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.