一、简介
Android设备,需要实时监控本机蓝牙连接其他蓝牙设备的状态,包含:连接、配对、开关3种状态。本文介绍了2种方法,各有优势,下面来到我的Studio一起瞅瞅吧~
二、定时器任务 + Handler + 功能方法
定时器任务 + Handler + 功能方法,此组合适用于页面初始化时、页面创建完毕后的2种情况,更新蓝牙连接状态的界面UI。
2.1 定时器任务
//在页面初始化加载时引用
updateInfoTimerTask();
private void updateInfoTimerTask() {
MyTimeTask infoTimerTask = new MyTimeTask(1000, new TimerTask() {
@Override
public void run() {
mHandler.sendEmptyMessage(1);
}
});
infoTimerTask.start();
}
//定时器任务工具类
import java.util.Timer;
import java.util.TimerTask;
public class MyTimeTask {
private Timer timer;
private TimerTask task;
private long time;
public MyTimeTask(long time, TimerTask task) {
this.task = task;
this.time = time;
if (timer == null){
timer = new Timer();
}
}
public void start(){
//每隔 time时间段 就执行一次
timer.schedule(task, 0, time);
}
public void stop(){
if (timer != null) {
timer.cancel();
if (task != null) {
//将原任务从队列中移除
task.cancel();
}
}
}
}
2.2 Handler
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1: {
//使用Handler发送定时任务消息,在页面初始化和应用运行中实时更新蓝牙的连接状态
checkBtDeviceConnectionStates(mContext);
}
break;
}
}
};
2.3 功能方法
public void checkBtDeviceConnectionStates(Context context) {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
Log.i(TAG, "checkBtDeviceConnectionStates():蓝牙设备不支持 或 未开启蓝牙");
//更新界面UI
itemTvLogBtStatus.setText(R.string.bt_connect_state_off);
return;
}
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices != null && !pairedDevices.isEmpty()) {
for (BluetoothDevice device : pairedDevices) {
// 检查 A2DP 连接状态(以 A2DP 为例)
boolean a2dpState = bluetoothAdapter.getProfileProxy(context, new BluetoothProfile.ServiceListener() {
@Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.A2DP) {
// 连接状态检查需要在这里进行,因为这是在服务连接后的回调中
int connectionState = ((BluetoothA2dp) proxy).getConnectionState(device);
switch (connecti