android实现蓝牙耳机的连接及列表的管理

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

先来看看具体效果:

1、添加权限

 
 
 
 
 
 
 

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()进行搜索,具体相关代码如下:

 @Override
    public boolean open() {//打开蓝牙 ture-打开成功
        if(mBluetoothadapter==null){
            return false;
        }
        return mBluetoothadapter.enable();
    }

    @Override
    public boolean close() {//关闭蓝牙
        if(mBluetoothadapter==null){
            return true;
        }
        return mBluetoothadapter.disable();
    }

    @Override
    public boolean startDiscovery() {//搜索蓝牙
        if(mBluetoothadapter==null){
            return false;
        }
        if (mBluetoothadapter.isDiscovering()) {
            mBluetoothadapter.cancelDiscovery();
        }

        return mBluetoothadapter.startDiscovery();
    }

    @Override
    public 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() {
         @Override
         public 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 devices=new ArrayList<>();
                 if(mBluetoothA2dp!=null){
//                     removeA2dpMacEqual();
                     List deviceList=mBluetoothA2dp.getConnectedDevices();
                     if(deviceList!=null&&deviceList.size()>0){
                         devices.addAll(deviceList);
                     }
                 }
                 if(mBluetoothHeadset!=null){
//                     removeHeadsetMacEqual();
                     List deviceList=mBluetoothHeadset.getConnectedDevices();
                     if(deviceList!=null&&deviceList.size()>0){
                         devices.addAll(deviceList);
                     }
                 }
                 mBTConnectListener.onConnectedDevice(devices);
             }
//             else if(profile == BluetoothProfile.HEALTH){//健康
//                 mBluetoothHealth = (BluetoothHealth) proxy;
//             }
         }

         @Override
         public 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;
//             }

         }
     };

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

 @Override
    public 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); //设置priority
        try {
            //通过反射获取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;

    @Override
    public 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); //设置priority
        try {
            //通过反射获取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();
        }
    }




    @Override
    public boolean open() {//打开蓝牙 ture-打开成功
        if(mBluetoothadapter==null){
            return false;
        }
        return mBluetoothadapter.enable();
    }

    @Override
    public boolean close() {//关闭蓝牙
        if(mBluetoothadapter==null){
            return true;
        }
        return mBluetoothadapter.disable();
    }

    @Override
    public boolean startDiscovery() {//搜索蓝牙
        if(mBluetoothadapter==null){
            return false;
        }
        if (mBluetoothadapter.isDiscovering()) {
            mBluetoothadapter.cancelDiscovery();
        }

        return mBluetoothadapter.startDiscovery();
    }

    @Override
    public boolean stopDiscovery() {//停止搜索蓝牙
        if(mBluetoothadapter==null||!mBluetoothadapter.isDiscovering()){
            return true;
        }
        return mBluetoothadapter.cancelDiscovery();
    }

    @Override
    public String getName() {//获取本地蓝牙名称
        if(mBluetoothadapter==null){
            return null;
        }
        return mBluetoothadapter.getName();
    }

    @Override
    public boolean setName(String name) {//设置蓝牙的名称
        if (mBluetoothadapter == null) {
            return false;
        }
        return mBluetoothadapter.setName(name);
    }

    @Override
    public String getAddress() {//获取本地蓝牙地址
        if(mBluetoothadapter==null){
            return null;
        }
        return mBluetoothadapter.getAddress();
    }

    @Override
    public boolean isEnable() {//蓝牙是否可用,即是否打开
        if(mBluetoothadapter==null){
            return false;
        }
        return mBluetoothadapter.isEnabled();
    }

    @Override
    public boolean isSupport() {//是否支持蓝牙
        return mBluetoothadapter==null?false:true;
    }

    @Override
    public Set getBondedDevices() {//获取以配对设备
        if(mBluetoothadapter==null){
            return null;
        }
        return mBluetoothadapter.getBondedDevices();
    }

    @Override
    public boolean createBond(BluetoothDevice device) {//配对
        if(device==null){
            return false;
        }
        return device.createBond();
    }

    @Override
    public 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;
        }
    }

    @Override
    public 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;
    }

    @Override
    public boolean disconnect(BluetoothDevice device) {
        boolean isDisconnect=false;
        if(mBluetoothA2dp!=null){
            List devices=mBluetoothA2dp.getConnectedDevices();
            if(devices!=null&&devices.contains(device)){
                Log.d(TAG,"disconnect A2dp");
                isDisconnect=disConnectA2dpAndHeadSet(BluetoothA2dp.class,mBluetoothA2dp,device);
            }
        }
        if(mBluetoothHeadset!=null){
            List 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);
    }

    @Override
    public void destroy() {
        if(mFilter!=null){
            mFilter=null;
            mContext.unregisterReceiver(mBluetoothReceiver);
        }
        isA2dpComplete=false;
        isHeadsetComplete=false;
        mBluetoothadapter.closeProfileProxy(BluetoothProfile.A2DP,mBluetoothA2dp);
        mBluetoothadapter.closeProfileProxy(BluetoothProfile.HEADSET,mBluetoothHeadset);

    }

    @Override
    public void getConnectedDevices() {
        if(isBackConDev){
            return;
        }
        isBackConDev=true;
        if(isA2dpComplete&&isHeadsetComplete){
            List devices=new ArrayList<>();
            if(mBluetoothA2dp!=null){
//                removeA2dpMacEqual();
                List deviceList=mBluetoothA2dp.getConnectedDevices();
                if(deviceList!=null&&deviceList.size()>0){

                    devices.addAll(deviceList);
                }
            }
            if(mBluetoothHeadset!=null){
//                removeHeadsetMacEqual();
                List 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 deviceList=mBluetoothA2dp.getConnectedDevices();
//        if(deviceList==null||deviceList.size()<1){
//            return;
//        }
//        for(int i=0;i deviceList=mBluetoothHeadset.getConnectedDevices();
//        if(deviceList==null||deviceList.size()<1){
//            return;
//        }
//        for(int i=0;i

最后给出demo的下载地址

你可能感兴趣的:(Android,android实现蓝牙耳机连接,蓝牙管理,android音箱连接,android蓝牙耳机开发,蓝牙耳机连接)