2013-03-05 21 views
1

我正在使用藍牙聊天示例,我正試圖從連接藍牙設備時處於活動狀態的線程以特定間隔發送「虛擬」數據。每隔一段時間啓動/停止另一個服務以調用原始服務中的方法是否是一個好主意?我將如何實現這一點?如何從服務中的線程以特定間隔運行方法...?

private class ConnectedThread extends Thread { 

    static private final String TAG = "PhoneInfoConnectedThread"; 
    private final BluetoothSocket mmSocket; 
    private final InputStream mmInStream; 
    private final OutputStream mmOutStream; 

    public ConnectedThread(BluetoothSocket socket, String socketType) { 
     mmSocket = socket; 
     InputStream tmpIn = null; 
     OutputStream tmpOut = null; 

     // Get the BluetoothSocket input and output streams 
     try { 
      tmpIn = socket.getInputStream(); 
      tmpOut = socket.getOutputStream(); 
      Log.d(TAG, "In and out streams created"); 
     } catch (IOException e) { 
      Log.e(TAG, "temp sockets not created " + e.getMessage()); 
     } 

     mmInStream = tmpIn; 
     mmOutStream = tmpOut; 
    } 

    // this is where we will spend out time when connected to the accessory. 
    public void run() { 
     // Keep listening to the InputStream while connected 
     while (true) { 
      // do whatever 
     } 
    } 

    // Write to the connected OutStream. 
    public void write(byte[] buffer) { 
     if (mmOutStream == null) { 
      Log.e(TAG, "ConnectedThread.write: no OutStream"); 
      return; 
     } 
     try { 
      Log.d(TAG, "ConnectedThread.write: writing " + buffer.length 
        + " bytes"); 
      mmOutStream.write(buffer); 

      // Share the sent message back to the UI Activity 
      // mHandler.obtainMessage(PhoneInfoActivity.MESSAGE_WRITE, -1, 
      // -1, buffer).sendToTarget(); 
      Log.d(TAG, "ConnectedThread.write: sent to calling activity"); 
     } catch (IOException e) { 
      Log.e(TAG, "Exception during write" + e.getMessage()); 
     } 
    } 

    public void cancel() { 
     try { 
      Log.d(TAG, "ConnectedThread.cancel: closing socket"); 
      if (mmSocket != null) 
       mmSocket.close(); 
     } catch (IOException e) { 
      Log.e(TAG, "ConnectedThread.cancel: socket.close() failed" 
        + e.getMessage()); 
     } 
    } 
} 

回答

1

這個例子可以幫助你。

MyTimerTask myTask = new MyTimerTask(); 
Timer myTimer = new Timer(); 
myTimer.schedule(myTask, 2000, 1000); 


class MyTimerTask extends TimerTask { 
    public void run() { 
    Log.v("TAG","Message"); 
    } 
} 

瞭解更多信息see this

相關問題