蓝牙通讯的主要操作路线 创建蓝牙适配器对象-扫描周围蓝牙设备-配对-连接完成之后通过蓝牙适配器对象通信 下一篇讲解
文章中有获取当前蓝牙设备链接状态的方法 低版本可能会出现配对没有连接成功的情况 可根据状态做出处理
首先申请权限
<uses-permission android:name="android.permission.BLUETOOTH" ></uses-permission>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" ></uses-permission>
创建BluetoothAdapter对象
private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
扫描广播
intentFilter1.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
intentFilter1.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
intentFilter1.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(scanBlueReceiver, intentFilter1);
配对广播
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
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(pinBlueReceiver, intentFilter);
开启扫描
/**
- 扫描的方法 返回true 扫描成功
- 通过接收广播获取扫描到的设备
- @return
*/
public boolean scanBlue() {
if (!isBlueEnable()) {
Log.e("蓝牙扫描", "Bluetooth not enable!");
return false;
}
//当前是否在扫描,如果是就取消当前的扫描,重新扫描
if (mBluetoothAdapter.isDiscovering()) {
// mBluetoothAdapter.cancelDiscovery();
Toast.makeText(this, "正在扫描中", Toast.LENGTH_SHORT).show();
} else {
//tvAddress.setText("");
//此方法是个异步操作,一般搜索12秒
return mBluetoothAdapter.startDiscovery();
}
return false;
}
开始配对
/**
* 配对(配对成功与失败通过广播返回)
*
* @param device
* @return
*/
public boolean pin(BluetoothDevice device) {
if (device == null) {