2016-09-24 71 views
1

我想發送五個數據到藍牙。第一個打開,第二個打開,第三個打開,等等......我想要打開和關閉之間的延遲時間(大約1秒)。哪一個是最好的。目前,我使用的睡眠Thread類發送消息到藍牙時,發送延遲是最好的方法嗎?

for (int i=1;i<5;i++) { 
      try { 
       if(i%2==0){ 
        send(1); 
        Thread.sleep(500); 
       } 
       else{   
        send(0); 
        Thread.sleep(500); 
       } 

      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 

回答

1

試試這個

private static final int STEP_ONE_COMPLETE = 0; 
private static final int STEP_TWO_COMPLETE = 1; 

... 

private doBackgroundUpdate1(){ 
    Thread backgroundThread = new Thread() { 
     @Override 
     public void run() { 
      // do first step 

      // finished first step 
      Message msg = Message.obtain(); 
      msg.what = STEP_ONE_COMPLETE; 
      handler.sendMessage(msg); 
     } 
    } 
    backgroundThread.start(); 
} 
private doBackgroundUpdate2(){ 
    Thread backgroundThread = new Thread() { 
     @Override 
     public void run() { 
      // do second step 

      // finished second step 
      Message msg = Message.obtain(); 
      msg.what = STEP_TWO_COMPLETE; 
      handler.sendMessage(msg); 
     } 
    } 
    backgroundThread.start(); 
} 
private Handler handler = new Handler(){ 
    @Override 
    public void handleMessage(Message msg) { 
     switch(msg.what){ 
     case STEP_ONE_COMPLETE: 
      doBackgroundUpdate2(); 
      break; 
     case STEP_TWO_COMPLETE: 
      // do final steps; 
      break; 
     } 
    } 
} 
+0

這麼久。我正在使用它在服務中。主要目標是兩個發送0和1之間的延遲 – user3051460