2015-10-05 39 views
0

應用程序崩潰,我無法使用了同樣的觀點在Timer類訪問查看從定時器或處理器

我需要的應用程序刷新值,通常在這種情況下顯示出來

Timer t = new Timer(); 
//Set the schedule function and rate 
    t.scheduleAtFixedRate(new TimerTask() { 

           @Override 
           public void run() { 
            //Called each time when 1000 milliseconds (1 second) (the period parameter) 
            find(v); 
           } 

          }, 
//Set how long before to start calling the TimerTask (in milliseconds) 
      0, 
//Set the amount of time between each execution (in milliseconds) 
      10000); 

public void find(View view) { 
    if (btAdapter.isDiscovering()) { 
     //the button is pressed when it discovers, so cancel the discovery 
     btAdapter.cancelDiscovery(); 
    } else { 
     BTArrayAdapter.clear(); 
     btAdapter.startDiscovery(); 

     registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); 
    } 
} 
+0

爲什麼你不試試find(null)而不是find(v),因爲你還沒有使用View? – geokavel

+0

仍然崩潰,顯然 - android.view.ViewRootImpl $ CalledFromWrongThreadException:只有創建視圖層次結構的原始線程可以觸及其視圖。 –

回答

0

你需要使用Activity.runOnUiThread()

Timer t = new Timer(); 
//Set the schedule function and rate 
    t.scheduleAtFixedRate(new TimerTask() { 

          @Override 
          public void run() { 
          //Called each time when 1000 milliseconds (1 second) (the period parameter) 
           runOnUiThread(new Runnable() { 

            public void run() {find(v);} 
          }); 
          } 

         }, 
//Set how long before to start calling the TimerTask (in milliseconds) 
      0, 
//Set the amount of time between each execution (in milliseconds) 
      10000); 
+0

工作:D,我也不得不聲明視圖v作爲一個全局變量,並使用您的代碼 –

+0

也,你能幫我把這個代碼添加到serivce?即使在關閉應用程序時,我仍然需要這個運行 –

+0

不幸的是我不知道 – geokavel