Bluetooth蓝牙

Posted by アライさん on 2019年10月22日

BluetoothDevice

BluetoothDevice.getBondState()获取绑定状态。
BluetoothDevice.BOND_BONDING:正在绑定
BluetoothDevice.BOND_BONDED:已经绑定
BluetoothDevice.BOND_NONE:未绑定

所需权限:

1
2
3
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

获取已绑定的蓝牙设备列表

1
2
3
4
5
6
7
BluetoothAdapter adapter =  BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> devices = adapter.getBondedDevices();
if (devices.size() > 0) {
for (BluetoothDevice device : devices) {
LogUtils.d(TAG, "已配对的设备:" +device.getName());
}
}

扫描蓝牙设备

和wifi类似,启动蓝牙扫描,然后接受扫描结果的广播
实测Android设置中的蓝牙,也只会扫描一次,用户点击扫描按钮才会再次扫描

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device != null) {
// 添加到ListView的Adapter。
LogUtils.d(TAG, device.getName());
}
}
}
};

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(receiver, intentFilter);

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
adapter.startDiscovery();

@Override
public void onDestroy() {
try {
adapter.cancelDiscovery();
unregisterReceiver(receiver);
} catch (Exception e) {
LogUtils.d(TAG, e.toString());
}
super.onDestroy();
}

打开关闭蓝牙

1
2
3
4
5
6
7
8
BluetoothAdapter adapter =  BluetoothAdapter.getDefaultAdapter();
if (adapter.isEnabled()){
adapter.disable();
tvBluetooth.setText("已关闭蓝牙");
}else{
adapter.enable();
tvBluetooth.setText("已开启蓝牙");
}

绑定蓝牙设备

绑定蓝牙会发送BluetoothDevice.ACTION_BOND_STATE_CHANGED广播

1
2
3
4
5
6
7
BluetoothDevice device = list.get(position);
try {
Method method = device.getClass().getMethod("createBond");
method.invoke(device);
} catch (Exception e) {
LogUtils.e(TAG, e.toString());
}

或者

1
2
BluetoothDevice device = list.get(position);
device.createBond();

解除绑定蓝牙设备

1
2
3
BluetoothDevice device = list.get(position);
Method removeBondMethod = device.getClass().getMethod("removeBond");
Boolean returnValue = (Boolean) removeBondMethod.invoke(device);