【Android】蓝牙相关
文章目录
- 前言
- 一、相关权限
- 二、获取蓝牙名称
- 蓝牙权限
- 检查是否支持蓝牙
- 查找设备
- 取消查找
- 获取已绑定的设备
- 获取当前已连接的设备
- 配对设备
- 取消配对
- 获取设备电量
- 获取设备主要类型
- 三、监听蓝牙状态
- 蓝牙开关状态
- 蓝牙连接状态
- 四、主动连接蓝牙
- 五、参考链接
前言
蓝牙的常用方法,获取、显示、查找、连接等方法,注意蓝牙自动连接需要先打开目的蓝牙的可见性,否则搜索不到。
一、相关权限
- android.permission.BLUETOOTH
蓝牙使用权限 - android.permission.BLUETOOTH_ADMIN
蓝牙管理权限 - android.permission.BLUETOOTH_PRIVILEGED
蓝牙配对权限
上述三个蓝牙普通权限,无需动态申请
二、获取蓝牙名称
蓝牙权限
<uses-permission android:name="android.permission.BLUETOOTH" />
校验并申请蓝牙权限
检查是否支持蓝牙
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();// 是否支持蓝牙,并且蓝牙已打开if (!(mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled())) {// 弹窗开启蓝牙,推荐startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), REQUEST_BLUETOOTH_OPEN);// 申请权限,开启蓝牙,系统倒计时弹窗提示是否开启// vivoS12开启无效,小米10可以开启boolean enable = mBluetoothAdapter.enable();}
查找设备
/*** 查找设备* 如果返回 false 尝试动态申请 {@link android.Manifest.permission#ACCESS_FINE_LOCATION} 权限** @return 查找成功返回 true,否则返回 false*/
public boolean discoveryDevice() {if (defaultAdapter.isDiscovering()){defaultAdapter.cancelDiscovery();}return defaultAdapter.startDiscovery();
}
取消查找
/*** 取消查找* @return 取消结果*/
public boolean cancelDiscovery() {return defaultAdapter.cancelDiscovery();
}
获取已绑定的设备
/*** 查找已经绑定的设备* @return 设备列表*/
public List<BluetoothDevice> getBoundDevice() {Set<BluetoothDevice> bondedDevices = defaultAdapter.getBondedDevices();return new ArrayList<>(bondedDevices);
}
获取当前已连接的设备
/*** 获取当前连接中的设备* 如果有多个设备连接,仅返回第一个** @return 连接中的设备*/
public BluetoothDevice getConnectedDevice() {List<BluetoothDevice> boundDevice = mBluetoothAdapter.getBondedDevices();for (BluetoothDevice bondedDevice : bondedDevices) {// 使用反射调用被隐藏的方法Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);isConnectedMethod.setAccessible(true);boolean isConnected = (boolean) isConnectedMethod.invoke(bondedDevice, (Object[]) null);if (connected) {return device;}}return null;
}
配对设备
/*** 配对设备* @param device 目标设备* @return 配对结果*/
public boolean createBound(BluetoothDevice device) {if (defaultAdapter.isDiscovering()) {defaultAdapter.cancelDiscovery();}try {Method createBond = device.getClass().getMethod("createBond");createBond.invoke(device);return true;} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {e.printStackTrace();return false;}
}
取消配对
/*** 取消与设备的配对* @param device 目标设备* @return 配对结果*/
public boolean cancelBound(BluetoothDevice device) {if (defaultAdapter.isDiscovering()) {defaultAdapter.cancelDiscovery();}try {Method removeBond = device.getClass().getMethod("removeBond");removeBond.invoke(device);return true;} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {e.printStackTrace();}return false;
}
获取设备电量
/*** 获取设备电量* @param device 设备* @return 电量*/
public int getDeviceBatteryLevel(BluetoothDevice device) {int level = 0;if (device == null) {return level;}try {Method getBatteryLevel = device.getClass().getMethod("getBatteryLevel", new Class[]{});getBatteryLevel.setAccessible(true);level = (int) getBatteryLevel.invoke(device);} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {e.printStackTrace();}return level;
}
获取设备主要类型
/*** 获取主要设备类型* 通过 {@link BluetoothDevice#getBluetoothClass()} 获取 BluetoothClass* 通过 {@link android.bluetooth.BluetoothClass#getMajorDeviceClass()} 获取设备的主要类型* 根据主要类型设置蓝牙列表的icon* 或判断设备类型是否为需要的设备等* @param device {@link BluetoothDevice}* @return 设备类型*/
public String getDeviceClassIc(BluetoothDevice device) {// 电脑final int COMPUTER = 0x0100;// 手机final int PHONE = 0x0200;// 媒体设备final int AUDIO_VIDEO = 0x0400;// 可穿戴设备final int WEARABLE = 0x0700;// 健康设备(BLE?)final int HEALTH = 0x0900;// 外设final int PERIPHERAL = 0x0500;// 其他final int MISC = 0x0000;final int NETWORKING = 0x0300;final int IMAGING = 0x0600;final int TOY = 0x0800;final int UNCATEGORIZED = 0x1F00;String deviceClassType = null;switch (device.getBluetoothClass().getMajorDeviceClass()) {case PERIPHERAL:deviceClassType = "外接设备";break;case COMPUTER:deviceClassType = "电脑";break;case PHONE:deviceClassType = "手机";break;case AUDIO_VIDEO:deviceClassType = "媒体设备";break;case WEARABLE:deviceClassType = "健康设备";break;default:deviceClassType = "其他";break;}return deviceClassType;
}
三、监听蓝牙状态
蓝牙开关状态
注册蓝牙开关状态监听
IntentFilter filter = new IntentFilter();filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);mContext.registerReceiver(mBleConnectReceiver, filter);private final BroadcastReceiver mBleConnectReceiver = new BroadcastReceiver() {public void onReceive(Context context, Intent intent) {String action = intent.getAction();if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);switch (state) {case BluetoothAdapter.STATE_OFF:// 蓝牙已关闭Logger.i(TAG, "isBluetooth is close ");break;case BluetoothAdapter.STATE_TURNING_OFF:// 蓝牙正在关闭break;case BluetoothAdapter.STATE_ON:// 蓝牙已打开Logger.i(TAG, "isBluetoothConnect true ");break;case BluetoothAdapter.STATE_TURNING_ON:// 蓝牙正在打开break;}}}};
蓝牙连接状态
注册蓝牙连接和断开状态监听
IntentFilter filter = new IntentFilter();filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);mContext.registerReceiver(mBleConnectReceiver, filter);private final BroadcastReceiver mBleConnectReceiver = new BroadcastReceiver() {public void onReceive(Context context, Intent intent) {String action = intent.getAction();// 蓝牙连接状态,仅本机蓝牙状态变化回调if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {Logger.i(TAG, "isBluetoothConnect true ");} else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {Logger.i(TAG, "isBluetoothConnect false ");}}}};
四、主动连接蓝牙
手车互联的自动连接方案
怎么主动连接蓝牙
1、先检查蓝牙权限,权限没开启跳转权限申请界面或阻止下一步并提示
2、检查蓝牙是否打开,没打开则主动打开蓝牙,蓝牙打开也有广播回调
3、打开蓝牙之后,开启广播扫描附近的蓝牙,准备发起连接(因为搜索附件的蓝牙费电,所以要定时轮询,做好关闭)
4、搜索到设备,可以加载已经配对过的蓝牙设备列表,点击列表连接指定的设备(或者自动重连,搜到哪个连接哪个)
5、执行配对的时候,会提示一个密钥确认弹窗需要用户确认
6、执行连接前要关闭搜索,蓝牙连接成功会有关闭回调,形成闭环
一加手机怎么连接上android studio 一加怎么连接蓝牙
五、参考链接
- Android Bluetooth相关操作