Android之蓝牙耳机的使用

*使用蓝牙所需的权限
*蓝牙使用之官方文档介绍
*获取蓝牙的开关状态
*判断蓝牙是否已经与设备连接
*蓝牙搜索附近的设备
*广播接收器(获取搜索到的设备信息,获取蓝牙的状态改变,获取连接设备状态的改变等等)
*主动连接一个蓝牙设备(先配对)
*断开蓝牙设备的连接
*获取蓝牙设备的风格
*获取蓝牙设备类型

1. 使用蓝牙所需的权限

 
    
    
   
    
    

2. 蓝牙使用之官方文档介绍

蓝牙API文档https://developer.android.google.cn/guide/topics/connectivity/bluetooth

操作蓝牙的两个基本类:
https://developer.android.google.cn/reference/android/bluetooth/BluetoothAdapter
https://developer.android.google.cn/reference/android/bluetooth/BluetoothDevice

3. 获取蓝牙的开关状态

//表示本地设备蓝牙适配器。可以执行基本的蓝牙任务,如启动设备发现,查询保税(配对)的设备列表
 BluetoothAdapter   mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (mBluetoothAdapter.isEnabled()) {
            //关闭蓝牙
            mBluetoothAdapter.disable();
        } else {
            //打开蓝牙
            mBluetoothAdapter.enable();
        }

4. 判断蓝牙是否已经与设备连接

 BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
            Class bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象
            //得到连接状态的方法
            Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
            //打开权限
            method.setAccessible(true);
            int state = (int) method.invoke(adapter, (Object[]) null);

            if (state == BluetoothAdapter.STATE_CONNECTED) {//蓝夜已经连接上设备,不一定是耳机
                //获取已经连接的蓝牙设备,有的手机可以同时连接多个设备,有的手机只能连接一个
                Set devices = adapter.getBondedDevices();

                for (BluetoothDevice device : devices) {
                    Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                    method.setAccessible(true);
                    //获取连接的状态
                    boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);
                    if (isConnected) {
                        if (device != null) {
                            //获取已经连接的设备信息
                            UILogUtils.e(TAG, "getConnectInfo    " + device.getAddress() + "  " + device.getName());
                            if (!device.getName().contains("EDIFIER")) {
                            }
                        }
                        deviceList.add(device);
                    }
                }
            } else {//蓝牙是打开状态,但是未连接任何设备
                //开启搜索,搜索附近的蓝牙设备
                startScanBluth();
            }

5. 蓝牙搜索附近的设备

 // 判断是否在搜索,如果在搜索,就取消搜索
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        // 开始搜索,搜索结果通过广播返回
        mBluetoothAdapter.startDiscovery();

6. 广播接收器(获取搜索到的设备信息,获取蓝牙的状态改变,获取连接设备状态的改变等等)

//这个广播过滤器自己根据需求添加,自己需要哪些状态的通知,就添加哪些,
//不清楚该注册哪些的 去官方文档查看对用的说明
https://developer.android.google.cn/reference/android/bluetooth/BluetoothAdapter
https://developer.android.google.cn/reference/android/bluetooth/BluetoothDevice

        IntentFilter filter = new IntentFilter();
      
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
        filter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
        filter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
        filter.addAction(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED);

        // 注册广播
        registerReceiver(receiver, filter);

这个是简单的蓝牙状态改变的广播

/**
     * 广播接收器
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 收到的广播类型
            String action = intent.getAction();
            // 从intent中获取设备
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (device != null) {
                UILogUtils.e(TAG, "receiver    " + device.getAddress() + "  " + device.getName());
            }

            if (TextUtils.isEmpty(action)) {
                return;
            }

            switch (action) {
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:// 搜索完成
                    UILogUtils.e(TAG, "receiver    " + "搜索完成");

                    // 关闭进度条
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                    break;
                case BluetoothAdapter.ACTION_STATE_CHANGED: //蓝牙开关状态的改变
                    UILogUtils.e(TAG, "receiver    " + "蓝牙开关状态的改变");

                   int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                        switch (blueState) {

                            case BluetoothAdapter.STATE_ON:
                                //蓝牙已打开
                                LogUtils.d(TAG, "蓝牙已打开");
                                if (listener != null) {
                                    listener.on();
                                }
                                break;
                            case BluetoothAdapter.STATE_OFF:
                                //蓝牙已关闭
                                LogUtils.d(TAG, "蓝牙已关闭");
                                if (listener != null) {
                                    listener.off();
                                }
                                if (BluetoothManager.getInstance().checkBLEFeature(context)) {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                                        BLEManager.getInstance().stopBleScan();
                                    }
                                }
                                break;
                            case BluetoothAdapter.STATE_TURNING_ON:
                                //蓝牙处于打开过程中,打开ing
                                LogUtils.d(TAG, "蓝牙打开中");
                                if (listener != null) {
                                    listener.turningOn();
                                }
                                break;
                            case BluetoothAdapter.STATE_TURNING_OFF:
                                //蓝牙处于关闭过程中,关闭ing
                                LogUtils.d(TAG, "蓝牙关闭中");
                                if (listener != null) {
                                    listener.turningOff();
                                }
                                break;
                            default:
                                break;

                        }
                    break;
                case BluetoothDevice.ACTION_FOUND://发现设备的广播
                    try {
                        UILogUtils.e(TAG, "receiver    " + "发现设备的广播");

                        // 没有配对
                        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                            if (!deviceList.contains(device)) {
                                deviceList.add(device);
                            }
                            if (!TextUtils.isEmpty(device.getName()) && device.getName().contains("EDIFIER")) {
                                name = device.getName();
                                mBluetoothAdapter.cancelDiscovery();
                                if (device.getBondState() == BluetoothDevice.BOND_NONE) {
                                    UILogUtils.e(TAG, "startConnent====" + "开始配对");
                                    Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
                                    Boolean result = (Boolean) createBondMethod.invoke(device);
                                } else if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                                    connet(device);
                                }
                                //                                startConnent(mBluetoothAdapter.getRemoteDevice(device.getAddress()));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case BluetoothDevice.ACTION_BOND_STATE_CHANGED: // 广播操作:表示远程设备的绑定状态发生变化。
                    UILogUtils.e(TAG, "receiver    " + "广播操作:表示远程设备的绑定状态发生变化。");

                    if (device.getName().equalsIgnoreCase(name)) {
                        switch (device.getBondState()) {
                            case BluetoothDevice.BOND_NONE:
                                //没有配对
                                break;
                            case BluetoothDevice.BOND_BONDING:
                                //配对中
                                break;
                            case BluetoothDevice.BOND_BONDED:
                                //配对完成
                                try {
                                    // 连接
                                    connet(device);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                break;
                        }
                    }
                    break;
                case BluetoothDevice.ACTION_ACL_CONNECTED: //广播操作:表示已与远程设备建立了低级别(ACL)连接
                    UILogUtils.e(TAG, "receiver    " + "广播操作:表示已与远程设备建立了低级别(ACL)连接");
                    break;
                default:
                    break;
            }
        }
    };

7. 主动连接一个蓝牙设备

连接一个设备需要先配对,如果已经配对过就可以直接连接

//与蓝牙设备配对 device是搜索到的蓝牙设备
 Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
 Boolean result = (Boolean) createBondMethod.invoke(device);

    /**
     * 连接设备
     *
     * @param device
     */
    private void connet(BluetoothDevice device) {
        // 固定的UUID
        try {
            final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
            UUID uuid = UUID.fromString(SPP_UUID);
            BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
            socket.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

8. 解除与蓝牙设备配对

 Method removeBondMethod = BluetoothDevice.class.getMethod("removeBond");
 Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);

9.获取蓝牙设备的风格

/**
     * 获取蓝牙设备的风格
     *
     * @param device
     * @return
     */
    public static String getBluetoothStyleString(BluetoothDevice device) {
        String style = "未知...";
        if (device != null) {
            int styleMajor = device.getBluetoothClass().getMajorDeviceClass();
            switch (styleMajor) {
                case BluetoothClass.Device.Major.AUDIO_VIDEO:
                    style = "音频设备";
                    break;
                case BluetoothClass.Device.Major.COMPUTER:
                    style = "电脑";
                    break;
                case BluetoothClass.Device.Major.HEALTH://健康状况
                    style = "健康状况";
                    break;
                case BluetoothClass.Device.Major.IMAGING://镜像,映像
                    style = "镜像";
                    break;
                case BluetoothClass.Device.Major.MISC:
                    style = "麦克风";
                    break;
                case BluetoothClass.Device.Major.NETWORKING:
                    style = "网络";
                    break;
                case BluetoothClass.Device.Major.PERIPHERAL:
                    style = "外部设备";
                    break;
                case BluetoothClass.Device.Major.PHONE:
                    style = "电话";
                    break;
                case BluetoothClass.Device.Major.TOY:
                    style = "玩具";
                    break;
                case BluetoothClass.Device.Major.UNCATEGORIZED:
                    style = "未知的";
                    break;
                case BluetoothClass.Device.Major.WEARABLE:
                    style = "穿戴设备";
                    break;
                default:
                    break;
            }
        }
        return style;
    }

10. 获取蓝牙设备类型

 /**
     * 获取蓝牙设备的类型
     *
     * @param device
     * @return
     */
    public static String getBluetoothTypeString(BluetoothDevice device) {
        String type = "未知的...";
        if (device != null) {
            int cls = device.getBluetoothClass().getDeviceClass();
            switch (cls) {
                case BluetoothClass.Device.AUDIO_VIDEO_CAMCORDER:
                    type = "录像机";
                    break;
                case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO:
                    type = "车载设备";
                    break;
                case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE:
                    type = "蓝牙耳机";
                    break;
                case BluetoothClass.Device.AUDIO_VIDEO_LOUDSPEAKER:
                    type = "扬声器";
                    break;
                case BluetoothClass.Device.AUDIO_VIDEO_MICROPHONE:
                    type = "麦克风";
                    break;
                case BluetoothClass.Device.AUDIO_VIDEO_PORTABLE_AUDIO:
                    type = "打印机";
                    break;
                case BluetoothClass.Device.AUDIO_VIDEO_SET_TOP_BOX:
                    type = "BOX";
                    break;
                case BluetoothClass.Device.AUDIO_VIDEO_UNCATEGORIZED:
                    type = "未知的";
                    break;
                case BluetoothClass.Device.AUDIO_VIDEO_VCR:
                    type = "录像机";
                    break;
                case BluetoothClass.Device.AUDIO_VIDEO_VIDEO_CAMERA:
                    type = "照相机录像机";
                    break;
                case BluetoothClass.Device.AUDIO_VIDEO_VIDEO_CONFERENCING:
                    type = "conferencing";
                    break;
                case BluetoothClass.Device.AUDIO_VIDEO_VIDEO_DISPLAY_AND_LOUDSPEAKER:
                    type = "显示器和扬声器";
                    break;
                case BluetoothClass.Device.AUDIO_VIDEO_VIDEO_GAMING_TOY:
                    type = "游戏";
                    break;
                case BluetoothClass.Device.AUDIO_VIDEO_VIDEO_MONITOR:
                    type = "可穿戴设备";
                    break;
                case BluetoothClass.Device.PHONE_CELLULAR:
                    type = "手机";
                    break;
                case BluetoothClass.Device.PHONE_CORDLESS:
                    type = "无线设备";
                    break;
                case BluetoothClass.Device.PHONE_ISDN:
                    type = "手机服务数据网";
                    break;
                case BluetoothClass.Device.PHONE_MODEM_OR_GATEWAY:
                    type = "手机调节器";
                    break;
                case BluetoothClass.Device.PHONE_SMART:
                    type = "手机卫星";
                    break;
                case BluetoothClass.Device.PHONE_UNCATEGORIZED:
                    type = "未知手机";
                    break;
                case BluetoothClass.Device.WEARABLE_GLASSES:
                    type = "可穿戴眼睛";
                    break;
                case BluetoothClass.Device.WEARABLE_HELMET:
                    type = "可穿戴头盔";
                    break;
                case BluetoothClass.Device.WEARABLE_JACKET:
                    type = "可穿戴上衣";
                    break;
                case BluetoothClass.Device.WEARABLE_PAGER:
                    type = "客串点寻呼机";
                    break;
                case BluetoothClass.Device.WEARABLE_UNCATEGORIZED:
                    type = "未知的可穿戴设备";
                    break;
                case BluetoothClass.Device.WEARABLE_WRIST_WATCH:
                    type = "手腕监听设备";
                    break;
                case BluetoothClass.Device.TOY_CONTROLLER:
                    type = "可穿戴设备";
                    break;
                case BluetoothClass.Device.TOY_DOLL_ACTION_FIGURE:
                    type = "玩具doll_action_figure";
                    break;
                case BluetoothClass.Device.TOY_GAME:
                    type = "游戏";
                    break;
                case BluetoothClass.Device.TOY_ROBOT:
                    type = "玩具遥控器";
                    break;
                case BluetoothClass.Device.TOY_UNCATEGORIZED:
                    type = "玩具未知设备";
                    break;
                case BluetoothClass.Device.TOY_VEHICLE:
                    type = "vehicle";
                    break;
                case BluetoothClass.Device.HEALTH_BLOOD_PRESSURE:
                    type = "健康状态-血压";
                    break;
                case BluetoothClass.Device.HEALTH_DATA_DISPLAY:
                    type = "健康状态数据";
                    break;
                case BluetoothClass.Device.HEALTH_GLUCOSE:
                    type = "健康状态葡萄糖";
                    break;
                case BluetoothClass.Device.HEALTH_PULSE_OXIMETER:
                    type = "健康状态脉搏血氧计";
                    break;
                case BluetoothClass.Device.HEALTH_PULSE_RATE:
                    type = "健康状态脉搏速来";
                    break;
                case BluetoothClass.Device.HEALTH_THERMOMETER:
                    type = "健康状态体温计";
                    break;
                case BluetoothClass.Device.HEALTH_WEIGHING:
                    type = "健康状态体重";
                    break;
                case BluetoothClass.Device.HEALTH_UNCATEGORIZED:
                    type = "未知健康状态设备";
                    break;
                case BluetoothClass.Device.COMPUTER_DESKTOP:
                    type = "电脑桌面";
                    break;
                case BluetoothClass.Device.COMPUTER_HANDHELD_PC_PDA:
                    type = "手提电脑或Pad";
                    break;
                case BluetoothClass.Device.COMPUTER_LAPTOP:
                    type = "便携式电脑";
                    break;
                case BluetoothClass.Device.COMPUTER_PALM_SIZE_PC_PDA:
                    type = "微型电脑";
                    break;
                case BluetoothClass.Device.COMPUTER_SERVER:
                    type = "电脑服务";
                    break;
                case BluetoothClass.Device.COMPUTER_UNCATEGORIZED:
                    type = "未知的电脑设备";
                    break;
                case BluetoothClass.Device.COMPUTER_WEARABLE:
                    type = "可穿戴的电脑";
                    break;
                case BluetoothClass.Device.AUDIO_VIDEO_HEADPHONES:
                    type = "头戴式受话器";
                    break;
                case BluetoothClass.Device.AUDIO_VIDEO_HIFI_AUDIO:
                    type = "高保真音频设备";
                    break;
                case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET:
                    type = "可穿戴耳机";
                    break;
                default:
                    break;

            }
        }
        return type;
    }

你可能感兴趣的:(Android之蓝牙耳机的使用)