随着物联网的发展,现在蓝牙设备越来越多了,像蓝牙耳机、蓝牙音箱等,那么怎样去连接管理这些设备呢,本文将通过蓝牙耳机做实例,来实现蓝牙的开关、搜索、配对、连接、设备蓝牙的可见性、获取蓝牙信息等;

先来看看具体效果:

1、添加权限

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.BLUETOOTH" /><uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /><uses-feature android:name="android.hardware.location.gps" /><uses-feature android:name="android.hardware.bluetooth_le" android:required="true" /><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

2、初始化

 mBluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);mBluetoothadapter = mBluetoothManager.getAdapter();

3、设置广播监听

  mFilter = new IntentFilter();mFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//状态改变mFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); //蓝牙开关状态mFilter.addAction(BluetoothDevice.ACTION_FOUND);//蓝牙发现新设备(未配对)mFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); //蓝牙开始搜索mFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); //蓝牙搜索结束mFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); //设备配对状态改变mFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);//设备建立连接mFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); //设备断开连接mFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED); //BluetoothAdapter连接状态mFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED); //BluetoothHeadset连接状态mFilter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED); //BluetoothA2dp连接状态

4、搜索蓝牙

搜索蓝牙之前要判断蓝牙是否打开,打开蓝牙可以使用enable()方法,当蓝牙打开后,调用startDiscovery()进行搜索,具体相关代码如下:

 @Overridepublic boolean open() {//打开蓝牙 ture-打开成功if(mBluetoothadapter==null){return false;}return mBluetoothadapter.enable();}@Overridepublic boolean close() {//关闭蓝牙if(mBluetoothadapter==null){return true;}return mBluetoothadapter.disable();}@Overridepublic boolean startDiscovery() {//搜索蓝牙if(mBluetoothadapter==null){return false;}if (mBluetoothadapter.isDiscovering()) {mBluetoothadapter.cancelDiscovery();}return mBluetoothadapter.startDiscovery();}@Overridepublic boolean stopDiscovery() {//停止搜索蓝牙if(mBluetoothadapter==null||!mBluetoothadapter.isDiscovering()){return true;}return mBluetoothadapter.cancelDiscovery();}

5、连接设备:

当搜索完成之后,找到要连接的设备进行连接,连接之前我们需要获取各种设备的相关代理服务,一般常用的代理服务有这两个种:BluetoothA2dp、BluetoothHeadset。BluetoothA2dp进行音频数据传送服务,BluetoothHeadset耳机相关服务。首页获取相关服务,具体代码如下:

   mBluetoothadapter.getProfileProxy(mContext,mProfileServiceListener, BluetoothProfile.A2DP);mBluetoothadapter.getProfileProxy(mContext,mProfileServiceListener, BluetoothProfile.HEADSET);

该方式没有直接方法相关服务代理,而是通过服务监听返回,mProfileServiceListener的相关代码如下:

 private BluetoothProfile.ServiceListener mProfileServiceListener=new BluetoothProfile.ServiceListener() {@Overridepublic void onServiceConnected(int profile, BluetoothProfile proxy) {Log.i(TAG, "onServiceConnected profile="+profile);if(profile == BluetoothProfile.A2DP){//播放音乐mBluetoothA2dp = (BluetoothA2dp) proxy; //转换isA2dpComplete=true;}else if(profile == BluetoothProfile.HEADSET){//打电话mBluetoothHeadset = (BluetoothHeadset) proxy;isHeadsetComplete=true;}if(isA2dpComplete&&isHeadsetComplete&&isBackConDev&&mBTConnectListener!=null){List<BluetoothDevice> devices=new ArrayList<>();if(mBluetoothA2dp!=null){
//                     removeA2dpMacEqual();List<BluetoothDevice> deviceList=mBluetoothA2dp.getConnectedDevices();if(deviceList!=null&&deviceList.size()>0){devices.addAll(deviceList);}}if(mBluetoothHeadset!=null){
//                     removeHeadsetMacEqual();List<BluetoothDevice> deviceList=mBluetoothHeadset.getConnectedDevices();if(deviceList!=null&&deviceList.size()>0){devices.addAll(deviceList);}}mBTConnectListener.onConnectedDevice(devices);}
//             else if(profile == BluetoothProfile.HEALTH){//健康
//                 mBluetoothHealth = (BluetoothHealth) proxy;
//             }}@Overridepublic void onServiceDisconnected(int profile) {Log.i(TAG, "onServiceDisconnected profile="+profile);if(profile == BluetoothProfile.A2DP){mBluetoothA2dp = null;}else if(profile == BluetoothProfile.HEADSET){mBluetoothHeadset = null;}
//             else if(profile == BluetoothProfile.HEALTH) {
//                 mBluetoothHealth = null;
//             }}};

获取相关的代理服务之后,就可以连接相应的设备了,具体相关代码如下:

 @Overridepublic boolean connect(BluetoothDevice device) {int styleMajor = device.getBluetoothClass().getMajorDeviceClass();boolean isConnect=false;switch (styleMajor) {case BluetoothClass.Device.Major.AUDIO_VIDEO://音频设备if(connectA2dpAndHeadSet(BluetoothHeadset.class,mBluetoothHeadset,device)){isConnect=true;}if(connectA2dpAndHeadSet(BluetoothA2dp.class,mBluetoothA2dp,device)){isConnect=true;}return isConnect;
//            case BluetoothClass.Device.Major.COMPUTER://电脑
//                break;
//            case BluetoothClass.Device.Major.HEALTH://健康状况
//                break;
//            case BluetoothClass.Device.Major.IMAGING://镜像,映像
//                break;case BluetoothClass.Device.Major.MISC://麦克风if(connectA2dpAndHeadSet(BluetoothHeadset.class,mBluetoothHeadset,device)){isConnect=true;}if(connectA2dpAndHeadSet(BluetoothA2dp.class,mBluetoothA2dp,device)){isConnect=true;}return isConnect;
//            case BluetoothClass.Device.Major.NETWORKING://网络
//                break;
//            case BluetoothClass.Device.Major.PERIPHERAL://外部设备
//                break;case BluetoothClass.Device.Major.PHONE://电话if(connectA2dpAndHeadSet(BluetoothHeadset.class,mBluetoothHeadset,device)){isConnect=true;}if(connectA2dpAndHeadSet(BluetoothA2dp.class,mBluetoothA2dp,device)){isConnect=true;}return isConnect;
//            case BluetoothClass.Device.Major.TOY://玩具
//                break;
//            case BluetoothClass.Device.Major.UNCATEGORIZED://未知的
//                break;
//            case BluetoothClass.Device.Major.WEARABLE://穿戴设备
//                break;}if(connectA2dpAndHeadSet(BluetoothHeadset.class,mBluetoothHeadset,device)){isConnect=true;}if(connectA2dpAndHeadSet(BluetoothA2dp.class,mBluetoothA2dp,device)){isConnect=true;}return isConnect;}/*** 连接A2dp 与 HeadSet* @param device* @param device*/private boolean connectA2dpAndHeadSet(Class btClass,BluetoothProfile bluetoothProfile,BluetoothDevice device){setPriority(device, 100); //设置prioritytry {//通过反射获取BluetoothA2dp中connect方法(hide的),进行连接。Method connectMethod =btClass.getMethod("connect",BluetoothDevice.class);connectMethod.setAccessible(true);connectMethod.invoke(bluetoothProfile, device);return true;} catch (Exception e) {e.printStackTrace();}return false;}/*** 设置优先级* 优先级是必要的,否则可能导致连接或断开连接失败等问题* @param device* @param priority*/private void setPriority(BluetoothDevice device, int priority) {if (mBluetoothA2dp == null) return;try {//通过反射获取BluetoothA2dp中setPriority方法(hide的),设置优先级Method connectMethod =BluetoothA2dp.class.getMethod("setPriority",BluetoothDevice.class,int.class);connectMethod.setAccessible(true);connectMethod.invoke(mBluetoothA2dp, device, priority);} catch (Exception e) {e.printStackTrace();}}

6、其他蓝牙设备的连接

不同的蓝牙设备,其功能也不相同,android中可以更具设备的类型来连接相应的服务,android中将设备大致分为如下如下几类,在代码中使用如下:

 int styleMajor = bluetoothDevice.getBluetoothClass().getMajorDeviceClass();//获取蓝牙主要分类switch (styleMajor) {case BluetoothClass.Device.Major.AUDIO_VIDEO://音频设备holder.img_signal.setImageResource(R.mipmap.icon_headset);break;case BluetoothClass.Device.Major.COMPUTER://电脑holder.img_signal.setImageResource(R.mipmap.icon_computer);break;case BluetoothClass.Device.Major.HEALTH://健康状况holder.img_signal.setImageResource(R.mipmap.icon_bluetooth);break;case BluetoothClass.Device.Major.IMAGING://镜像,映像holder.img_signal.setImageResource(R.mipmap.icon_bluetooth);break;case BluetoothClass.Device.Major.MISC://麦克风holder.img_signal.setImageResource(R.mipmap.icon_bluetooth);break;case BluetoothClass.Device.Major.NETWORKING://网络holder.img_signal.setImageResource(R.mipmap.icon_bluetooth);break;case BluetoothClass.Device.Major.PERIPHERAL://外部设备holder.img_signal.setImageResource(R.mipmap.icon_bluetooth);break;case BluetoothClass.Device.Major.PHONE://电话holder.img_signal.setImageResource(R.mipmap.icon_phone);break;case BluetoothClass.Device.Major.TOY://玩具holder.img_signal.setImageResource(R.mipmap.icon_bluetooth);break;case BluetoothClass.Device.Major.UNCATEGORIZED://未知的holder.img_signal.setImageResource(R.mipmap.icon_bluetooth);break;case BluetoothClass.Device.Major.WEARABLE://穿戴设备holder.img_signal.setImageResource(R.mipmap.icon_bluetooth);break;}

通过蓝牙主要分类来区分不同类型的设备,之后再通过相应的服务代理连接设备,android相关的服务代理如下:

 public boolean getProfileProxy(Context context, BluetoothProfile.ServiceListener listener,int profile) {if (context == null || listener == null) return false;if (profile == BluetoothProfile.HEADSET) {BluetoothHeadset headset = new BluetoothHeadset(context, listener);return true;} else if (profile == BluetoothProfile.A2DP) {BluetoothA2dp a2dp = new BluetoothA2dp(context, listener);return true;} else if (profile == BluetoothProfile.A2DP_SINK) {BluetoothA2dpSink a2dpSink = new BluetoothA2dpSink(context, listener);return true;} else if (profile == BluetoothProfile.AVRCP_CONTROLLER) {BluetoothAvrcpController avrcp = new BluetoothAvrcpController(context, listener);return true;} else if (profile == BluetoothProfile.INPUT_DEVICE) {BluetoothInputDevice iDev = new BluetoothInputDevice(context, listener);return true;} else if (profile == BluetoothProfile.PAN) {BluetoothPan pan = new BluetoothPan(context, listener);return true;} else if (profile == BluetoothProfile.HEALTH) {BluetoothHealth health = new BluetoothHealth(context, listener);return true;} else if (profile == BluetoothProfile.MAP) {BluetoothMap map = new BluetoothMap(context, listener);return true;} else if (profile == BluetoothProfile.HEADSET_CLIENT) {BluetoothHeadsetClient headsetClient = new BluetoothHeadsetClient(context, listener);return true;} else if (profile == BluetoothProfile.SAP) {BluetoothSap sap = new BluetoothSap(context, listener);return true;} else if (profile == BluetoothProfile.PBAP_CLIENT) {BluetoothPbapClient pbapClient = new BluetoothPbapClient(context, listener);return true;} else if (profile == BluetoothProfile.MAP_CLIENT) {BluetoothMapClient mapClient = new BluetoothMapClient(context, listener);return true;} else if (profile == BluetoothProfile.INPUT_HOST) {BluetoothInputHost iHost = new BluetoothInputHost(context, listener);return true;} else {return false;}}

可以根据具体的设备来获取相应的服务,获取的方式跟获取BluetoothA2dp、BluetoothHeadset的方式是一致的。
好了,到这里基本上要的的功能的实现完了,下面将BluetoothHelper类的带放到下面,面时具体相关的功能实现:

package com.qt.bluetooth.bluetooth;import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.util.Log;import com.qt.bluetooth.bluetooth.interfaces.IBTBoudListener;
import com.qt.bluetooth.bluetooth.interfaces.IBTConnectListener;
import com.qt.bluetooth.bluetooth.interfaces.IBTScanListener;
import com.qt.bluetooth.bluetooth.interfaces.IBTStateListener;
import com.qt.bluetooth.bluetooth.interfaces.IBluetoothHelper;import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;/***@date 2019/7/23*@desc 蓝牙辅助类**/public class BluetoothHelper implements IBluetoothHelper {private final String TAG="BluetoothHelper";private Context mContext;private BluetoothManager mBluetoothManager;private BluetoothAdapter mBluetoothadapter;private BluetoothA2dp mBluetoothA2dp;private BluetoothHeadset mBluetoothHeadset;
//    private BluetoothHealth mBluetoothHealth;private IntentFilter mFilter;private IBTStateListener mBTStateListener;//蓝牙状态监听private IBTScanListener mBTScanListener;//蓝牙搜索监听private IBTBoudListener mBTBoudListener;//蓝牙绑定监听private IBTConnectListener mBTConnectListener;//连接监听private boolean isBackConDev;//是否返回已连接的设备private boolean isA2dpComplete,isHeadsetComplete;@Overridepublic void init(Context context) {mContext=context.getApplicationContext();mBluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);mBluetoothadapter = mBluetoothManager.getAdapter();isA2dpComplete=false;isHeadsetComplete=false;mBluetoothadapter.getProfileProxy(mContext,mProfileServiceListener, BluetoothProfile.A2DP);mBluetoothadapter.getProfileProxy(mContext,mProfileServiceListener, BluetoothProfile.HEADSET);
//        mBluetoothadapter.getProfileProxy(mContext,mProfileServiceListener, BluetoothProfile.HEALTH);if(mFilter==null){mContext.registerReceiver(mBluetoothReceiver,makeFilter());}}private IntentFilter makeFilter() {if(mFilter==null){mFilter = new IntentFilter();mFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//状态改变mFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); //蓝牙开关状态mFilter.addAction(BluetoothDevice.ACTION_FOUND);//蓝牙发现新设备(未配对)mFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); //蓝牙开始搜索mFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); //蓝牙搜索结束mFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); //设备配对状态改变mFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);//设备建立连接mFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); //设备断开连接mFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED); //BluetoothAdapter连接状态mFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED); //BluetoothHeadset连接状态mFilter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED); //BluetoothA2dp连接状态}return mFilter;}/*** 连接A2dp 与 HeadSet* @param device* @param device*/private boolean connectA2dpAndHeadSet(Class btClass,BluetoothProfile bluetoothProfile,BluetoothDevice device){setPriority(device, 100); //设置prioritytry {//通过反射获取BluetoothA2dp中connect方法(hide的),进行连接。Method connectMethod =btClass.getMethod("connect",BluetoothDevice.class);connectMethod.setAccessible(true);connectMethod.invoke(bluetoothProfile, device);return true;} catch (Exception e) {e.printStackTrace();}return false;}/*** 断开A2dp 与 HeadSet* @param device*/private boolean disConnectA2dpAndHeadSet(Class btClass,BluetoothProfile bluetoothProfile,BluetoothDevice device){setPriority(device, 0);try {//通过反射获取BluetoothA2dp中connect方法(hide的),断开连接。Method connectMethod =btClass.getMethod("disconnect",BluetoothDevice.class);connectMethod.setAccessible(true);connectMethod.invoke(bluetoothProfile, device);return true;} catch (Exception e) {e.printStackTrace();}return false;}/*** 设置优先级* 优先级是必要的,否则可能导致连接或断开连接失败等问题* @param device* @param priority*/private void setPriority(BluetoothDevice device, int priority) {if (mBluetoothA2dp == null) return;try {//通过反射获取BluetoothA2dp中setPriority方法(hide的),设置优先级Method connectMethod =BluetoothA2dp.class.getMethod("setPriority",BluetoothDevice.class,int.class);connectMethod.setAccessible(true);connectMethod.invoke(mBluetoothA2dp, device, priority);} catch (Exception e) {e.printStackTrace();}}@Overridepublic boolean open() {//打开蓝牙 ture-打开成功if(mBluetoothadapter==null){return false;}return mBluetoothadapter.enable();}@Overridepublic boolean close() {//关闭蓝牙if(mBluetoothadapter==null){return true;}return mBluetoothadapter.disable();}@Overridepublic boolean startDiscovery() {//搜索蓝牙if(mBluetoothadapter==null){return false;}if (mBluetoothadapter.isDiscovering()) {mBluetoothadapter.cancelDiscovery();}return mBluetoothadapter.startDiscovery();}@Overridepublic boolean stopDiscovery() {//停止搜索蓝牙if(mBluetoothadapter==null||!mBluetoothadapter.isDiscovering()){return true;}return mBluetoothadapter.cancelDiscovery();}@Overridepublic String getName() {//获取本地蓝牙名称if(mBluetoothadapter==null){return null;}return mBluetoothadapter.getName();}@Overridepublic boolean setName(String name) {//设置蓝牙的名称if (mBluetoothadapter == null) {return false;}return mBluetoothadapter.setName(name);}@Overridepublic String getAddress() {//获取本地蓝牙地址if(mBluetoothadapter==null){return null;}return mBluetoothadapter.getAddress();}@Overridepublic boolean isEnable() {//蓝牙是否可用,即是否打开if(mBluetoothadapter==null){return false;}return mBluetoothadapter.isEnabled();}@Overridepublic boolean isSupport() {//是否支持蓝牙return mBluetoothadapter==null?false:true;}@Overridepublic Set<BluetoothDevice> getBondedDevices() {//获取以配对设备if(mBluetoothadapter==null){return null;}return mBluetoothadapter.getBondedDevices();}@Overridepublic boolean createBond(BluetoothDevice device) {//配对if(device==null){return false;}return device.createBond();}@Overridepublic boolean removeBond(BluetoothDevice device) {//取消配对Class btDeviceCls = BluetoothDevice.class;Method removeBond = null;try {removeBond = btDeviceCls.getMethod("removeBond");removeBond.setAccessible(true);return (boolean) removeBond.invoke(device);} catch (Exception e) {e.printStackTrace();return false;}}@Overridepublic boolean connect(BluetoothDevice device) {int styleMajor = device.getBluetoothClass().getMajorDeviceClass();boolean isConnect=false;switch (styleMajor) {case BluetoothClass.Device.Major.AUDIO_VIDEO://音频设备if(connectA2dpAndHeadSet(BluetoothHeadset.class,mBluetoothHeadset,device)){isConnect=true;}if(connectA2dpAndHeadSet(BluetoothA2dp.class,mBluetoothA2dp,device)){isConnect=true;}return isConnect;
//            case BluetoothClass.Device.Major.COMPUTER://电脑
//                break;
//            case BluetoothClass.Device.Major.HEALTH://健康状况
//                break;
//            case BluetoothClass.Device.Major.IMAGING://镜像,映像
//                break;case BluetoothClass.Device.Major.MISC://麦克风if(connectA2dpAndHeadSet(BluetoothHeadset.class,mBluetoothHeadset,device)){isConnect=true;}if(connectA2dpAndHeadSet(BluetoothA2dp.class,mBluetoothA2dp,device)){isConnect=true;}return isConnect;
//            case BluetoothClass.Device.Major.NETWORKING://网络
//                break;
//            case BluetoothClass.Device.Major.PERIPHERAL://外部设备
//                break;case BluetoothClass.Device.Major.PHONE://电话if(connectA2dpAndHeadSet(BluetoothHeadset.class,mBluetoothHeadset,device)){isConnect=true;}if(connectA2dpAndHeadSet(BluetoothA2dp.class,mBluetoothA2dp,device)){isConnect=true;}return isConnect;
//            case BluetoothClass.Device.Major.TOY://玩具
//                break;
//            case BluetoothClass.Device.Major.UNCATEGORIZED://未知的
//                break;
//            case BluetoothClass.Device.Major.WEARABLE://穿戴设备
//                break;}if(connectA2dpAndHeadSet(BluetoothHeadset.class,mBluetoothHeadset,device)){isConnect=true;}if(connectA2dpAndHeadSet(BluetoothA2dp.class,mBluetoothA2dp,device)){isConnect=true;}return isConnect;}@Overridepublic boolean disconnect(BluetoothDevice device) {boolean isDisconnect=false;if(mBluetoothA2dp!=null){List<BluetoothDevice> devices=mBluetoothA2dp.getConnectedDevices();if(devices!=null&&devices.contains(device)){Log.d(TAG,"disconnect A2dp");isDisconnect=disConnectA2dpAndHeadSet(BluetoothA2dp.class,mBluetoothA2dp,device);}}if(mBluetoothHeadset!=null){List<BluetoothDevice> devices=mBluetoothHeadset.getConnectedDevices();if(devices!=null&&devices.contains(device)){Log.d(TAG,"disconnect Headset");isDisconnect=disConnectA2dpAndHeadSet(BluetoothHeadset.class,mBluetoothHeadset,device);}}return isDisconnect;
//        int styleMajor = device.getBluetoothClass().getMajorDeviceClass();
//        switch (styleMajor) {
//            case BluetoothClass.Device.Major.AUDIO_VIDEO://音频设备
//                return disConnectA2dpAndHeadSet(BluetoothA2dp.class,device);
//            case BluetoothClass.Device.Major.COMPUTER://电脑
//                break;
//            case BluetoothClass.Device.Major.HEALTH://健康状况
//                return disConnectA2dpAndHeadSet(BluetoothHealth.class,device);
//            case BluetoothClass.Device.Major.IMAGING://镜像,映像
//                break;
//            case BluetoothClass.Device.Major.MISC://麦克风
//                break;
//            case BluetoothClass.Device.Major.NETWORKING://网络
//                break;
//            case BluetoothClass.Device.Major.PERIPHERAL://外部设备
//                break;
//            case BluetoothClass.Device.Major.PHONE://电话
//                return disConnectA2dpAndHeadSet(BluetoothHeadset.class,device);
//            case BluetoothClass.Device.Major.TOY://玩具
//                break;
//            case BluetoothClass.Device.Major.UNCATEGORIZED://未知的
//                break;
//            case BluetoothClass.Device.Major.WEARABLE://穿戴设备
//                break;
//        }
//        return disConnectA2dpAndHeadSet(BluetoothA2dp.class,device);}@Overridepublic void destroy() {if(mFilter!=null){mFilter=null;mContext.unregisterReceiver(mBluetoothReceiver);}isA2dpComplete=false;isHeadsetComplete=false;mBluetoothadapter.closeProfileProxy(BluetoothProfile.A2DP,mBluetoothA2dp);mBluetoothadapter.closeProfileProxy(BluetoothProfile.HEADSET,mBluetoothHeadset);}@Overridepublic void getConnectedDevices() {if(isBackConDev){return;}isBackConDev=true;if(isA2dpComplete&&isHeadsetComplete){List<BluetoothDevice> devices=new ArrayList<>();if(mBluetoothA2dp!=null){
//                removeA2dpMacEqual();List<BluetoothDevice> deviceList=mBluetoothA2dp.getConnectedDevices();if(deviceList!=null&&deviceList.size()>0){devices.addAll(deviceList);}}if(mBluetoothHeadset!=null){
//                removeHeadsetMacEqual();List<BluetoothDevice> deviceList=mBluetoothHeadset.getConnectedDevices();if(deviceList!=null&&deviceList.size()>0){devices.addAll(deviceList);}}mBTConnectListener.onConnectedDevice(devices);isBackConDev=false;}}//    /**
//     * 移除A2dp mac相等设备
//     */
//    private void removeA2dpMacEqual(){
//        if(mBluetoothA2dp==null){
//            return;
//        }
//        List<BluetoothDevice> deviceList=mBluetoothA2dp.getConnectedDevices();
//        if(deviceList==null||deviceList.size()<1){
//            return;
//        }
//        for(int i=0;i<deviceList.size();){
//            BluetoothDevice bluetoothDevice=deviceList.get(i);
//            boolean isSkip=false;
//            for(int j=i+1;j<deviceList.size();){
//                BluetoothDevice device=deviceList.get(j);
//                if(!TextUtils.isEmpty(device.getAddress())&&device.getAddress().equals(bluetoothDevice.getAddress())){
//                    isSkip=true;
//                    if(mBluetoothA2dp.getConnectionState(bluetoothDevice) == BluetoothA2dp.STATE_CONNECTED){
//                        deviceList.remove(device);
//                    }else if(mBluetoothA2dp.getConnectionState(device) == BluetoothA2dp.STATE_CONNECTED){
//                        deviceList.remove(bluetoothDevice);
//                    }else{
//                        deviceList.remove(bluetoothDevice);
//                    }
//                    break;
//                }
//                j++;
//            }
//            if(isSkip){
//                continue;
//            }
//            i++;
//        }
//    }//    /**
//     * 移除Headset mac相等设备
//     */
//    private void removeHeadsetMacEqual(){
//        if(mBluetoothHeadset==null){
//            return;
//        }
//        List<BluetoothDevice> deviceList=mBluetoothHeadset.getConnectedDevices();
//        if(deviceList==null||deviceList.size()<1){
//            return;
//        }
//        for(int i=0;i<deviceList.size();){
//            BluetoothDevice bluetoothDevice=deviceList.get(i);
//            boolean isSkip=false;
//            for(int j=i+1;j<deviceList.size();){
//                BluetoothDevice device=deviceList.get(j);
//                if(!TextUtils.isEmpty(device.getAddress())&&device.getAddress().equals(bluetoothDevice.getAddress())){
//                    isSkip=true;
//                    if(mBluetoothHeadset.getConnectionState(bluetoothDevice) == BluetoothHeadset.STATE_CONNECTED){
//                        deviceList.remove(device);
//                    }else if(mBluetoothHeadset.getConnectionState(device) == BluetoothHeadset.STATE_CONNECTED){
//                        deviceList.remove(bluetoothDevice);
//                    }else{
//                        deviceList.remove(bluetoothDevice);
//                    }
//                    break;
//                }
//                j++;
//            }
//            if(isSkip){
//                continue;
//            }
//            i++;
//        }
//    }@Overridepublic boolean isConnected(BluetoothDevice device) {//是否连接if(mBluetoothA2dp!=null&&mBluetoothA2dp.getConnectionState(device) == BluetoothA2dp.STATE_CONNECTED){Log.d(TAG,"isConnected name="+device.getName());
//            removeA2dpMacEqual();List<BluetoothDevice> bluetoothDeviceList=mBluetoothA2dp.getConnectedDevices();if(bluetoothDeviceList!=null&&bluetoothDeviceList.size()>0){for(BluetoothDevice bluetoothDevice:bluetoothDeviceList){if(!TextUtils.isEmpty(device.getAddress())&&device.getAddress().equals(bluetoothDevice.getAddress())){return true;}}}}if(mBluetoothHeadset!=null&&mBluetoothHeadset.getConnectionState(device) == BluetoothHeadset.STATE_CONNECTED){Log.d(TAG,"isConnected name="+device.getName());
//            removeHeadsetMacEqual();List<BluetoothDevice> bluetoothDeviceList=mBluetoothHeadset.getConnectedDevices();if(bluetoothDeviceList!=null&&bluetoothDeviceList.size()>0){for(BluetoothDevice bluetoothDevice:bluetoothDeviceList){if(!TextUtils.isEmpty(device.getAddress())&&device.getAddress().equals(bluetoothDevice.getAddress())){return true;}}}}return false;}@Overridepublic boolean setDiscoverableTimeout(int timeout) {try {//得到指定的类中的方法
//            Method method = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);
//            method.setAccessible(true);
//            method.invoke(mBluetoothadapter, timeout);//根据测试,发现这一函数的参数无论传递什么值,都是永久可见的Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout",int.class);setDiscoverableTimeout.setAccessible(true);Method setScanMode =BluetoothAdapter.class.getMethod("setScanMode",int.class,int.class);setScanMode.setAccessible(true);setDiscoverableTimeout.invoke(mBluetoothadapter,timeout);setScanMode.invoke(mBluetoothadapter,BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE,timeout);return true;} catch (Exception e) {Log.d(TAG,"setDiscoverableTimeout msg="+e.getMessage());e.printStackTrace();}return false;}@Overridepublic void setBTStateListener(IBTStateListener btStateListener) {mBTStateListener=btStateListener;}@Overridepublic void setBTScanListener(IBTScanListener btScanListener) {mBTScanListener=btScanListener;}@Overridepublic void setBTBoudListener(IBTBoudListener btBoudListener) {mBTBoudListener=btBoudListener;}@Overridepublic void setBTConnectListener(IBTConnectListener btConnectListener) {mBTConnectListener=btConnectListener;}//A2dpprivate BluetoothProfile.ServiceListener mProfileServiceListener=new BluetoothProfile.ServiceListener() {@Overridepublic void onServiceConnected(int profile, BluetoothProfile proxy) {Log.i(TAG, "onServiceConnected profile="+profile);if(profile == BluetoothProfile.A2DP){//播放音乐mBluetoothA2dp = (BluetoothA2dp) proxy; //转换isA2dpComplete=true;}else if(profile == BluetoothProfile.HEADSET){//打电话mBluetoothHeadset = (BluetoothHeadset) proxy;isHeadsetComplete=true;}if(isA2dpComplete&&isHeadsetComplete&&isBackConDev&&mBTConnectListener!=null){List<BluetoothDevice> devices=new ArrayList<>();if(mBluetoothA2dp!=null){
//                     removeA2dpMacEqual();List<BluetoothDevice> deviceList=mBluetoothA2dp.getConnectedDevices();if(deviceList!=null&&deviceList.size()>0){devices.addAll(deviceList);}}if(mBluetoothHeadset!=null){
//                     removeHeadsetMacEqual();List<BluetoothDevice> deviceList=mBluetoothHeadset.getConnectedDevices();if(deviceList!=null&&deviceList.size()>0){devices.addAll(deviceList);}}mBTConnectListener.onConnectedDevice(devices);}
//             else if(profile == BluetoothProfile.HEALTH){//健康
//                 mBluetoothHealth = (BluetoothHealth) proxy;
//             }}@Overridepublic void onServiceDisconnected(int profile) {Log.i(TAG, "onServiceDisconnected profile="+profile);if(profile == BluetoothProfile.A2DP){mBluetoothA2dp = null;}else if(profile == BluetoothProfile.HEADSET){mBluetoothHeadset = null;}
//             else if(profile == BluetoothProfile.HEALTH) {
//                 mBluetoothHealth = null;
//             }}};private BroadcastReceiver mBluetoothReceiver=new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();BluetoothDevice dev;int state;if (action == null) {return;}switch (action) {/*** 蓝牙开关状态* int STATE_OFF = 10; //蓝牙关闭* int STATE_ON = 12; //蓝牙打开* int STATE_TURNING_OFF = 13; //蓝牙正在关闭* int STATE_TURNING_ON = 11; //蓝牙正在打开*/case BluetoothAdapter.ACTION_STATE_CHANGED:state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);if(mBTStateListener!=null){mBTStateListener.onStateChange(state);}break;/*** 蓝牙开始搜索*/case BluetoothAdapter.ACTION_DISCOVERY_STARTED:Log.i(TAG, "蓝牙开始搜索");if(mBTScanListener!=null){mBTScanListener.onScanStart();}break;/*** 蓝牙搜索结束*/case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:Log.i(TAG, "蓝牙扫描结束");if(mBTScanListener!=null){mBTScanListener.onScanStop(null);}break;/*** 发现新设备*/case BluetoothDevice.ACTION_FOUND:dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//                    short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,(short)0);//信号强度if(mBTScanListener!=null){mBTScanListener.onFindDevice(dev);}break;/*** 设备配对状态改变* int BOND_NONE = 10; //配对没有成功* int BOND_BONDING = 11; //配对中* int BOND_BONDED = 12; //配对成功*/case BluetoothDevice.ACTION_BOND_STATE_CHANGED:dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);if(mBTBoudListener!=null){mBTBoudListener.onBondStateChange(dev);}Log.i(TAG, "设备配对状态改变:" + dev.getBondState());break;/*** 设备建立连接* int STATE_DISCONNECTED = 0; //未连接* int STATE_CONNECTING = 1; //连接中* int STATE_CONNECTED = 2; //连接成功*/case BluetoothDevice.ACTION_ACL_CONNECTED:dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);Log.i(TAG, "设备建立连接:" + dev.getBondState());
//                    mCallback.onConnect(dev);break;/*** 设备断开连接*/case BluetoothDevice.ACTION_ACL_DISCONNECTED:dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);// mCallback.onConnect(dev.getBondState(), dev);break;/*** 本地蓝牙适配器* BluetoothAdapter连接状态*/case BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED:dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);Log.i(TAG, "Adapter STATE: " + intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, 0));Log.i(TAG, "BluetoothDevice: " + dev.getName() + ", " + dev.getAddress());break;/*** 提供用于手机的蓝牙耳机支持* BluetoothHeadset连接状态*/case BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED:dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);Log.i(TAG, "Headset STATE: " + intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, 0));Log.i(TAG, "BluetoothDevice: " + dev.getName() + ", " + dev.getAddress());switch (intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, -1)) {case BluetoothHeadset.STATE_CONNECTING://连接中if(mBTConnectListener!=null){mBTConnectListener.onConnecting(dev);}break;case BluetoothHeadset.STATE_CONNECTED://已连接if(mBTConnectListener!=null){mBTConnectListener.onConnected(dev);}break;case BluetoothHeadset.STATE_DISCONNECTED://断开if(mBTConnectListener!=null){mBTConnectListener.onDisConnect(dev);}break;case BluetoothHeadset.STATE_DISCONNECTING://断开中if(mBTConnectListener!=null){mBTConnectListener.onDisConnecting(dev);}break;}break;/*** 定义高质量音频可以从一个设备通过蓝牙连接传输到另一个设备* BluetoothA2dp连接状态*/case BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED:dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);switch (intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, -1)) {case BluetoothA2dp.STATE_CONNECTING:Log.i(TAG,"A2dp device: " + dev.getName() + " connecting");if(mBTConnectListener!=null){mBTConnectListener.onConnecting(dev);}break;case BluetoothA2dp.STATE_CONNECTED:Log.i(TAG,"A2dp device: " + dev.getName() + " connected");if(mBTConnectListener!=null){mBTConnectListener.onConnected(dev);}break;case BluetoothA2dp.STATE_DISCONNECTING:Log.i(TAG,"A2dp device: " + dev.getName() + " disconnecting");if(mBTConnectListener!=null){mBTConnectListener.onDisConnecting(dev);}break;case BluetoothA2dp.STATE_DISCONNECTED:Log.i(TAG,"A2dp device: " + dev.getName() + " disconnected");if(mBTConnectListener!=null){mBTConnectListener.onDisConnect(dev);}break;default:break;}default:break;}}};
}

最后给出demo的下载地址

android实现蓝牙耳机的连接及列表的管理相关推荐

  1. android蓝牙耳机接入,Android跟蓝牙耳机建立连接有两种方式

    2. 蓝牙耳机主动跟Android 连首先BluetoothAudioGateway 会在一个线程中收到来自蓝牙耳机的RFCOMM 连接,然后发送消息给BluetoothHeadsetService. ...

  2. android 蓝牙耳机 判断,Android实现蓝牙耳机连接

    前言 最近看了下蓝牙耳机连接的问题,查阅了相关资料,再此做一个总结. 本文参考以下链接: Android实现主动连接蓝牙耳机 再次对作者表示感谢. 今天涉及的内容有: 流程讲解 新建广播Bluetoo ...

  3. Android实现蓝牙耳机连接

    代码地址如下: http://www.demodashi.com/demo/13259.html 前言 讲讲android对于蓝牙耳机连接技术的实现 今天涉及的内容有: 1. 流程讲解 2. 新建广播 ...

  4. android 连接蓝牙耳机 播放音乐,android 手机怎么实现和蓝牙耳机建立连接,连接之后可以听音乐...

    如题,手机和蓝牙耳机配对之后,怎么建立连接 解决方案 20 BluetoothA2dpService是底层的Service类,你可以通过BluetoothA2dp类来使用它 android.bluet ...

  5. Android BLE与终端通信(二)——Android Bluetooth基础搜索蓝牙设备显示列表

    Android BLE与终端通信(二)--Android Bluetooth基础搜索蓝牙设备显示列表 摘要 第一篇算是个热身,这一片开始来写些硬菜了,这篇就是实际和蓝牙打交道了,所以要用到真机调试哟, ...

  6. win10连接蓝牙耳机_苹果手机蓝牙耳机无法连接怎么办?

    大家平时在使用苹果手机时,可能会遇到蓝牙耳机无法连接的情况.蓝牙耳机不能于手机连接,有多种因素,小编在这里为大家介绍一些常用解决无法连接蓝牙耳机的方法,希望可以帮到你. 重启设备 如果苹果手机和蓝牙耳 ...

  7. Android应用性能优化之优化列表头像过度绘制[一]

    为什么80%的码农都做不了架构师?>>>    操作的是否顺畅.卡顿,决定着整体的流畅程度. 事实上android跟iphone的差别,个人觉得很大程度上决定于流畅程度,无论是动画, ...

  8. android设备如何苹果,Android安卓设备如何连接Mac的方法

    Android安卓设备如何连接Mac的方法 本篇文章主要给大家总结了安卓设备连接MAC电脑的方法以及中间遇到连接问题以后的处理办法. 平时大家用到最多的就是安卓手机和苹果电脑互连,由于安卓系统应用广泛 ...

  9. Android手机HC-05蓝牙连接Arduino nano获取DHT-11温湿度传感器数据

    如果您觉得本文对您有用,希望您点赞,收藏并且把它分享出去,不明白的可以在评论区留言,我会一一解答,感谢您的支持!! 目标 Android手机HC-05蓝牙连接Arduino nano获取DHT-11温 ...

最新文章

  1. 一篇关于java变量定义的文章
  2. 头条一面竟然问我Maven?
  3. 13. sizeof 和 strlen 的区别
  4. @NotNull 、@NotBlank、@NotEmpty区别
  5. 设计模式之_Iterator_02
  6. 消灭编译警告(Warning)
  7. http请求的基本过程
  8. OPPO 推出 10 亿引力计划,全力构建智能化服务生态
  9. cartographer探秘之文章索引
  10. 设计师,程序员,当心字体侵权
  11. 重命名从喜马拉雅下载的音频文件
  12. 非谓语动词作后置定语
  13. winxp怎么打开无线网络服务器,WinXP无线网络设置的方法
  14. c语言设计程序实现顺序冒泡_计算机C语言编程设计专业知识题库汇总
  15. 读书、生活经典语录随笔
  16. 只有快递单号,怎样查询物流进度查看正在派件的单号
  17. C# 调用微信接口上传素材和发送图文消息
  18. HTML 表格与表单 个人简历
  19. 5.2 PMBOK--收集需求
  20. Jessi-开源项目知识点

热门文章

  1. 【日记本砸】21.04.16-31 他们身旁也有窗,却没有人向外眺望。
  2. bat for循环_bat教程[285] FOR/F options选项中usebackq的用法
  3. 人工神经网络的数学内涵,神经网络的数学表达式
  4. Java微信公众号开发(附源码!!!)
  5. IO HANG是什么
  6. 38家公司上榜2020大中华区最佳职场;中国新生代企业家调研白皮书正式发布 | 美通企业日报...
  7. 你是哪种类型的代码斗士
  8. macOS 上安装 PECL
  9. Python random模块(获取随机数)常用方法和使用例子
  10. WIN 10 又出诡异Bug,访问特定本地设备导致系统崩溃