获取所连接的蓝牙设备的连接状态
为了使用蓝牙,我们首先需要添加以下的权限:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
蓝牙连接和断开以后都会发送广播,我们可以通过接受广播信息,来获取当前蓝牙的连接状态;要接收的两个广播是:
BluetoothDevice.ACTION_ACL_DISCONNECTED
BluetoothDevice.ACTION_ACL_CONNECTED
第一个是当连接断开时发送的广播,第二个是当连接成功时发送的广播;
在Activity中注册一个广播接收器,用于接收此广播
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
registerReceiver(blueStateReceiver, intentFilter);
private BroadcastReceiver blueStateRecevier = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if(BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){
Log.e("connection", "connected " + device.getAddress());
}
else if(BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)){
Log.e("connection", "disconncted " + device.getAddress());
}
}
};
当接收到广播时,会自动调用onReceive函数,这时可以判断蓝牙的连接状态,和连接的蓝牙设备的信息;
在Activity中调用了registerReceiver后还需要在onDestroy中调用unregisterReceiver函数;