2016-04-23 65 views
0

我試圖做一個程序,當我按下按鈕時,它會顯示我的arduino汽車的速度和行駛距離。我試圖不斷更新TextView中的距離。Android Studio線程處理程序

這裏是我的處理程序中的onCreate()應當設置我的TextView文本距離的初始化:

mHandler = new Handler() { 
     public void handleMessage(Message msg) { 
      Bundle bundle = msg.getData(); 
      String stringss = bundle.getString("myKey"); 
      tv2 = (TextView) findViewById(R.id.zval); 
      tv2.setText("Distance is : " + stringss); 
     } 
    }; 

這裏是我的線程做背景

btnDist.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Runnable runnable = new Runnable() { 
       public void run() { 
        Message msg = mHandler.obtainMessage(); 
        Bundle bundle = new Bundle(); 
        int distance = distanta(); //function that returns distance/secound 
        int dist = 0; 
        while(distance > 0) { 
         try { 
          Thread.sleep(1000);     //1000 milliseconds is one second. 
         } catch (InterruptedException ex) { 
          Thread.currentThread().interrupt(); 
         } 

         dist += distance; 
        } 
         String dateString = String.valueOf(dist); 
         msg(dateString); 
         bundle.putString("myKey", dateString); 
         msg.setData(bundle); 
         mHandler.sendMessage(msg); 

       } 
      }; 
      Thread mythread = new Thread(runnable); 
      mythread.start(); 
     } 
    }); 

工作應用程序運行並不會崩潰,但我的textview根本不會更新。 我是新來的Java線程,所以我可能做錯了什麼。謝謝!

回答

0

試試這個找到的Arduino的時間旅行:

TextView TimerBox; 
long startTime = 0; 

Handler timerHandler = new Handler(); 

//this updates the textbox 
Runnable timerRunnable = new Runnable() { 
    @Override 
    public void run() { 
     long millis = System.currentTimeMillis() - startTime; 
     int seconds = (int) (millis/1000); 
     int decis = (int) ((millis % 1000)/10); 

     TimerBox.setText(String.format("Time: %d.%02d", seconds, decis)); 
     timerHandler.postDelayed(this, 10); 
    } 
}; 

這與初始化將更新計時器TextView的特定功能的新的處理程序。

當你希望它運行,這個代碼:

startTime = System.currentTimeMillis(); 

timerHandler.postDelayed(timerRunnable, 0); 

,當你想讓它停下來,用這個:

timerHandler.removeCallbacks(timerRunnable); 

該解決方案將要求您計算行駛距離自己基於速度和加速度。

+0

這非常有幫助,謝謝你的答案。 –

0

它不起作用的原因是因爲Handler默認情況下在其創建的線程上運行消息處理程序。在你的例子中,這是線程mythread。這意味着你正嘗試從不同於通常不工作的UI線程的不同線程更新UI。

它可以通過指定在其上處理程序應運行Looper,像mHandler = new Handler(Looper.getMainLooper()) {

+0

它沒有工作,距離變量應該加上當前距離,只要汽車繼續行駛,值應該繼續增加。我制定了一個計時器,並多次提供賽車的速度和時間來獲得距離。謝謝你的回答和你的時間! –

0

對不起,這是一種誤解是固定的。這不是我的代碼,我唯一的代碼僅在智揚傑弗裏呂的回答這個

if(seconds == 2){ 
seconds = 0; 
decis = 0; 
} 

我只是無法評論,因爲我的代表處是不夠的,我只是想知道如何閱讀可變

+0

他沒有提供問題的答案。一旦你有足夠的[聲譽](http://stackoverflow.com/help/whats-reputation),你將可以在任何帖子上[評論](http://stackoverflow.com/help/privileges/comment)。另外檢查這[我可以做什麼,而不是](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an-i-do-instead )。 – thewaywewere