2016-03-05 43 views
1

我嘗試製作一個ProgressDialog,顯示用戶與藍牙設備連接的進度,但進度對話框停留在0%,藍牙設備未連接。當我在onCreate()中調用函數時,它會連接,但當我這樣做時,我不會有ProgressDialog。Android 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

Ed它: 嗯,還是老樣子沒有工作:(

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:

​​

但現在ProgressDialog根本沒有出現:(當我點擊啓動活動的按鈕時,屏幕會變黑並凍結,wh藍牙連接時,它會加載佈局。從未顯示過ProgressDialog。

+0

使用runOnUiThread方法:[http://stackoverflow.com/a/11140429/5207572](http: //stackoverflow.com/a/11140429/5207572) –

回答

0

Android本身包含一個很好的API,用於需要與主UI線程交互的後臺進程。爲此,它將爲您節省所有繁重的工作,使您對所有線程操作非常輕鬆(內部使用Thread,Handler,Executor,ThreadPoolExecutorFutureTask等等)。

檢查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.

在鏈接中提到
+0

這是一個超出我的Java技能的範圍,您能編輯我的腳本嗎?Thanx;) –

+0

對不起@JulesHummelink I不能爲你做,參考http://developer.android.com/reference/android/os/AsyncTask.html是爲傻瓜編寫的,甚至有一個名爲'DownloadFilesTask'的例子,他們使用'onProgressUpdate'方法像使用'loading.setProgress(0)'一樣更新progressView,你至少應該嘗試讀取和編寫代碼,沒有其他辦法可以提高你的Java技能,如果我爲你寫出來,向前邁進,相信我。 – GoRoS

+1

好吧,我要去嘗試一下,thx爲你提供幫助。 –

0

我想你想從一個新的線程更新ProgressDialog,但它是在UI線程上創建的。你不能那樣做。查看您的IDE的輸出日誌。 看看這個link添加runOnUiThread方法。

它適用於OnCreate,因爲代碼是由UI線程執行的。

+0

那麼,我該怎麼做? –

+0

與runOnUiThread包裝你運行的情況下是這樣的: 新主題( runOnUiThread(新的Runnable(){// 運行功能 }); )。開始(); –

+0

它不工作: 新主題: –