安卓获取蓝牙状态

来源:互联网 发布:织梦cms模板安装目录 编辑:程序博客网 时间:2024/06/04 20:02

笔者最近一直在做蓝牙状态获取方面的事情,总结出一套获取蓝牙状态的代码,分享如下:

private BluetoothAdapter    ba    ;             //蓝牙适配器ba = BluetoothAdapter.getDefaultAdapter(); //蓝牙适配器是否存在,即是否发生了错误if (ba == null){   isBlueCon = -1;     //error}else if(ba.isEnabled()){   int a2dp = ba.getProfileConnectionState(BluetoothProfile.A2DP);//可操控蓝牙设备,如带播放暂停功能的蓝牙耳机   int headset = ba.getProfileConnectionState(BluetoothProfile.HEADSET);//蓝牙头戴式耳机,支持语音输入输出   int health = ba.getProfileConnectionState(BluetoothProfile.HEALTH);//蓝牙穿戴式设备   //查看是否蓝牙是否连接到三种设备的一种,以此来判断是否处于连接状态还是打开并没有连接的状态   int flag = -1;   if (a2dp == BluetoothProfile.STATE_CONNECTED) {      flag = a2dp;   } else if (headset == BluetoothProfile.STATE_CONNECTED) {      flag = headset;   } else if (health == BluetoothProfile.STATE_CONNECTED) {      flag = health;   }   //说明连接上了三种设备的一种   if (flag != -1){      isBlueCon = 1;//discontinued   }   else if (flag == -1){      NetworkInfo netInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_BLUETOOTH);      if (netInfo == null) {         isBlueCon = 1;//discontinued      }      else {         State blt  = netInfo.getState();         isBlueCon = getDevState(blt);         //系统内部,返回连接与否      }   }}else {   isBlueCon = 2;//shut off}



public static enum State {        CONNECTED,        CONNECTING,        DISCONNECTED,        DISCONNECTING,        SUSPENDED,        UNKNOWN;        private State() {        }    }



1 0
原创粉丝点击