学习目标:
项目中需求:连接上蓝牙后 显示蓝牙设备电量图标 并实时更新
学习内容:安卓蓝牙电量。
学习时间:2022.03.23
首先网上我调查到的关于蓝牙电量的文章大概有两种,
1.一种是可以通过反射 int level = (int)batteryMethod.invoke(device, (Object[]) null);,来调用,level就是当前蓝牙电量百分比。测试中车机连接手机拿到的数值一直是-1,而连接蓝牙耳机的时候,可以正常获取到耳机的电量,继续调查无果后我换了第二种方法。
2.用广播监听电量改变,这种方法通过注册广播对蓝牙设备电量进行监听,然后接收端接收到广播后,将蓝牙设备的电量传到int类型的变量中。
BluetoothListener:
case BluetoothHeadsetClient.ACTION_AG_EVENT:
int BatLevel=intent.getInExtra(BluetoothHeadsetClient.EXTRA_BATTERY_LEVEL, -1 );
PowerControllerImpl:
private InterFilter mBluetoothFilter;
mBluetoothFilter=new IntentFilter();
mBluetoothFilter.addAction(BluetoothHeadsetClient.ACTION_AG_EVENT);
mBluetoothListener=new BluetoothListener(this);
mContext.registerRecevier(mBluetoothListener,mBluetoothFilter);
上机测试通过。