2014-07-24 13 views
0

幫助下面我有這個代碼是在我的主要活動。基本上,只要我點擊按鈕,它將首先檢查是否設置了報警,如果它是假的,它將進入讀取連接設備上的RSSI直到其高於RSSI值的循環。我的問題是,我如何讓這個循環不會崩潰我的應用程序,它目前所做的。另外由於某些原因,mRSSI文本字段永遠不會填充RSSI值。有人能幫助我嗎?這是我需要完成的應用程序中的最後一件事。需要關於如何延遲或在後臺運行功能(android應用程序)

public void onMonitorClick(final View view){ 
    if (isBLEEnabled()) { 
     if (!isDeviceConnected()) { 
      // do nothing 
     } else if (isImmediateAlertOn == true) { 
      showMonitor(); 
      DebugLogger.v(TAG, "app is high alert"); 
      isImmediateAlertOn = true; 
     } 
     else { 
      DebugLogger.v(TAG, "app is no alert"); 
      hideMonitor(); 
      while(monitorStop != 1) 
      { 

      ((ProximityService.ProximityBinder) getService()).getRssi(); 
      rssilevel = ((ProximityService.ProximityBinder) getService()).getRssiValue(); 
      if (rssilevel > -50) { 
       DebugLogger.v(TAG, "greater then -50"); 
       monitorStop = 1; 
      } 
      mRSSI.setText("-" + String.valueOf(rssilevel) + "dB"); 
      isImmediateAlertOn = false; 
      mFindMeButton.setEnabled(false); 

      } 
     } 
    } else { 
     showBLEDialog(); 
    } 
} 

編輯重做代碼

public void onMonitorClick(final View view){ 
    if (isBLEEnabled()) { 
     if (!isDeviceConnected()) { 
       // do nothing 
      } else if (monitorvis == 0) { 
       showMonitor();    

     } else if (isImmediateAlertOn == true) { 
      showMonitor(); 
      DebugLogger.v(TAG, "app is high alert"); 
      isImmediateAlertOn = true; 
     } 
     else { 
      DebugLogger.v(TAG, "app is no alert"); 
      hideMonitor(); 
      monitorStop = 0; 
      do { run(); run2(); } while(monitorStop != 1); 

     } 
    } else { 
     showBLEDialog(); 
    } 
} 


protected void run() { 
    runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
      ((ProximityService.ProximityBinder) getService()).getRssi(); 
      rssilevel = ((ProximityService.ProximityBinder) getService()).getRssiValue(); 
      mRSSI.setText("-" + String.valueOf(rssilevel) + "dB"); 

     } 
    }); 
} 

protected void run2() { 
    runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
      mRSSI.setText("-" + String.valueOf(rssilevel) + "dB"); 
      if (rssilevel < -60) 
      { 
       monitorStop = 1; 
       showMonitor(); 
       ((ProximityService.ProximityBinder) getService()).startImmediateAlert(); 
      } 

     } 
    }); 
} 

回答

3

這是(IMHO)延遲一段代碼的執行的最簡單的方法:

new Handler().postDelayed(new Runnable() { 
    @Override 
    public void run() { 
     // Do what you need to do 
    } 
}, MILISECONDS_BEFORE_EXECUTION); 

這裏,MILISECONDS_BEFORE_EXECUTION是一個值(恆定的或變量)在執行代碼之前需要等待的毫秒數。 Documentation of Handler in Android

+0

我覺得自己像一個白癡,但我怎麼混合這與我的代碼。我還沒有那麼有經驗。 – user3808748

+0

您需要在延遲模式下運行的代碼是什麼? –

+0

如何修改上面編輯的代碼以延遲時間,還有爲什麼當mRSSI再次按下按鈕時沒有設置其他文本? – user3808748

相關問題