1.权限
在清单文件里添加权限
蓝牙权限 <uses-permission android:name="android.permission.BLUETOOTH" />
2.开启蓝牙时发送广播
action: BluetoothAdapter.ACTION_STATE_CHANGED
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); switch (state) { case BluetoothAdapter.STATE_OFF: Log.d("aaa", "STATE_OFF 手机蓝牙关闭"); break; case BluetoothAdapter.STATE_TURNING_OFF: Log.d("aaa", "STATE_TURNING_OFF 手机蓝牙正在关闭"); break; case BluetoothAdapter.STATE_ON: Log.d("aaa", "STATE_ON 手机蓝牙开启"); break; case BluetoothAdapter.STATE_TURNING_ON: Log.d("aaa", "STATE_TURNING_ON 手机蓝牙正在开启"); break; } }
3.蓝牙配对和解除配对时发送的广播
action: BluetoothDevice.ACTION_BOND_STATE_CHANGED
if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); String name = device.getName(); Log.d("aaa", "device name: " + name); int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1); switch (state) { case BluetoothDevice.BOND_NONE: Log.d("aaa", "解除配对"); break; case BluetoothDevice.BOND_BONDING: Log.d("aaa", "正在配对"); break; case BluetoothDevice.BOND_BONDED: Log.d("aaa", "配对成功"); break; } }
4.蓝牙设备连接和断开的广播
action: BluetoothDevice.ACTION_ACL_CONNECTED
BluetoothDevice.ACTION_ACL_DISCONNECTED
if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); }