2014-08-28 98 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 
      } 
     } 
    } 


    } 

回答