Android蓝牙开发前,首先要区分是经典蓝牙开发还是BLE(低功耗)蓝牙开发,它们的开发是有区别的,如果还分不清经典蓝牙和BLE(低功耗)蓝牙的小伙伴,可以先问问度娘。
开发流程:
- 开启蓝牙
- 扫描蓝牙
- 配对蓝牙
- 连接蓝牙
- 通信
1.先获取蓝牙的服务对象
private BluetoothManager bluetoothManager(Context context) { return (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); }
2.获取BluetoothAdapter对象
public BluetoothAdapter getBluetoothAdapter(Context context) { return bluetoothManager(context).getAdapter(); }
3.查看设备支不支持蓝牙功能
/** * 设备是否支持蓝牙 true为支持 * * @return */ public boolean isSupportBlue(Context context) { return null != getBluetoothAdapter(context); }
4.开启蓝牙权限
/**
* 自动打开蓝牙(异步:蓝牙不会立刻就处于开启状态)
* 这个方法打开蓝牙不会弹出提示
*/
public void openBlueAsyn(){
if (isSupportBlue()) {
mBluetoothAdapter.enable();
}
}
/**
* 自动打开蓝牙(同步)
* 这个方法打开蓝牙会弹出提示
* 需要在onActivityResult 方法中判断resultCode == RESULT_OK true为成功
*/
public void openBlueSync(Activity activity, int requestCode){
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
activity.startActivityForResult(intent, requestCode);
}
记得添加权限啊:
<!-- 使用蓝牙的权限 -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<!-- 扫描蓝牙设备或者操作蓝牙设置 -->
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!--模糊定位权限,仅作用于6.0+-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!--精准定位权限,仅作用于6.0+-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
话不多说直接copy吧,至于为什么要加定位权限。我也没有深究,这里6.0+记得加上动态申请定位权限的。不加,你懂的。。
在这之后才开始扫描蓝牙设备;扫描有低功耗扫描和经典扫描之分;
public BLEManager scanBle(Context context) { bluetoothLeScanner = getBluetoothAdapter(context).getBluetoothLeScanner(); bluetoothLeScanner.startScan(scanCallback); return this; }
/** * 扫描回调 */ ScanCallback scanCallback = new ScanCallback() { @Override public void onScanResult(int callbackType, ScanResult result) { super.onScanResult(callbac