2014-08-28 59 views
0

這是我的代碼。我想定期查看藍牙狀態

我想將android連接到arduino。 但我想檢查藍牙狀態,因爲用戶可以關閉藍牙。 在那個時候,我不希望那個藍牙狀態欄保持'連接'。

我試過用Thread來代替BroadcastReceiver。那麼我的代碼不會導致錯誤,但是線程不起作用。

也許在撥打藍牙活動時,線程無法做些什麼。

使用BroadcastReceiver更好嗎?

private static final int REQUEST_CONNECT_DEVICE = 1; 
private static final int REQUEST_ENABLE_BT = 2; 

private BluetoothAdapter bluetoothAdapter = null; 

private BluetoothThread btThread; 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 

     if(bluetoothAdapter == null) { 
      Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show(); 
      finish(); 
      return; 
     }  

    bluetoothConnect(); 

    btThread = new BluetoothThread(); 
    btThread.start(); 


} 


private void bluetoothConnect() { 

     if(!bluetoothAdapter.isEnabled()){ 
      changeBtStatus(CONNECTING); 
      Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
      startActivityForResult(enableIntent, REQUEST_ENABLE_BT); 

     } else{ 
      changeBtStatus(CONNECTED); 
      ensureDiscoverable(); 
     } 


} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     // TODO Auto-generated method stub 
    if(requestCode == REQUEST_ENABLE_BT){ 
     if(bluetoothAdapter.isEnabled()) { 
      changeBtStatus(CONNECTED); 
      ensureDiscoverable(); 
     } else{ 
      changeBtStatus(DISCONNECTED); 

     } 
    } 
} 

class BluetoothThread extends Thread{ 

    @Override 
    public void run() { 
     // TODO Auto-generated method stub 
     super.run(); 

     while(true){ 
      try{ 
       Thread.sleep(3000); 
       bluetoothConnect(); 
      }catch(InterruptedException e){ 
       //do noop 
      } 
     } 
    } 


    } 

回答