一、需求背景
客户在使用我公司的Flutter插件时,要求有一个蓝牙与设备重连的功能,我用公司提供的Android SDK只能实现超出和进入蓝牙范围进行重连,但是无法在蓝牙打开进行重连,这不得不让我使用Android手写一个广播监听。
二、实现步骤
添加权限
创建一个类继承 BroadcastReceiver
动态注册和注销广播
监听蓝牙状态
三、代码分享
1. 添加权限
在 AndroidManifest.xml 中添加蓝牙权限
2. 创建一个类继承 BroadcastReceiver
public class BLEStateReceiver extends BroadcastReceiver { private static final String BLE_STATE_OFF = "android.bluetooth.BluetoothAdapter.STATE_OFF"; private static final String BLE_STATE_ON = "android.bluetooth.BluetoothAdapter.STATE_ON"; private static BLEStateReceiver receiver = new BLEStateReceiver(); public static void register(Context context) { IntentFilter filter = new IntentFilter(); filter.setPriority(Integer.MAX_VALUE); // 监视蓝牙关闭和打开的状态 filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); filter.addAction(BLE_STATE_OFF); filter.addAction(BLE_STATE_ON); context.registerReceiver(receiver, filter); } public static void unregister(Context context) { context.unregisterReceiver(receiver); } @Override public void onReceive(final Context context, Intent intent) { // 检测蓝牙状态的逻辑 }}
3. 动态注册和注销广播
我这里是在 ActivityAware 的生命周期中注册的,你可以根据实际情况进行注册,只要在应用运行时注册就行。
public class MoyoungBlePlugin implements ActivityAware { private Activity activity; @Override public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) { activity = binding.getActivity(); // 注册广播 BLEStateReceiver.register(activity); } @Override public void onDetachedFromActivityForConfigChanges() { } @Override public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) { } @Override public void onDetachedFromActivity() { // 注销广播 BLEStateReceiver.unregister(activity); activity = null; }}
4. 监听蓝牙状态
我这里只监听了蓝牙的两种状态,如果想要监听多种状态可以查看参考。
public class BLEStateReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, Intent intent) { checkBLEState(context, intent); } private synchronized void checkBLEState(Context context, Intent intent) { int BLEState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0); switch (BLEState) { case BluetoothAdapter.STATE_ON: // 蓝牙已经打开 break; case BluetoothAdapter.STATE_TURNING_OFF: // 蓝牙正在关闭 break; } }}
四、参考文案
Android监听蓝牙与设备连接状态、关闭和打开状态_android 蓝牙连接状态监听_MasonYyp的博客-CSDN博客
来源地址:https://blog.csdn.net/m0_68349563/article/details/130561526