Android 蓝牙开发(搜索篇)

目录

蓝牙搜索-经典蓝牙搜索步骤:

经典蓝牙搜索实现关键代码: 

 蓝牙搜索-低功耗蓝牙搜索步骤:

 低功耗蓝牙搜索实现关键代码:

蓝牙模块类型和蓝牙设备类型获取: 

效果图:


需要权限

//Android 6.0以上需要处理权限
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

 

蓝牙搜索-经典蓝牙搜索步骤:

  1. 获取默认的蓝牙适配器
  2. 判断设备是否支持经典蓝牙
  3. 注册广播,用于监听搜索蓝牙时的各种动作
  4. 实现广播接收器,监听搜索蓝牙时的各种动作
  5. 通过蓝牙适配器获取绑定设备列表
  6. 搜索蓝牙

经典蓝牙搜索实现关键代码: 

//获取默认的蓝牙适配器
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//判断设备是否支持经典蓝牙
if (mBluetoothAdapter == null) {
    LogUtil.e("经典蓝牙","Device does not support Bluetooth");
} else {
    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }
}
//注册广播,用于监听搜索蓝牙时的各种动作
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//发现设备
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);//开始搜索
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//结束搜索
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//蓝牙模块状态改变(如打开或关闭)
registerReceiver(mReceiver, intentFilter);

//搜索前获取绑定设备列表
mBluetoothAdapter.getBondedDevices();
//搜索蓝牙
mBluetoothAdapter.startDiscovery();

//广播接收器,监听搜索蓝牙时的各种动作
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        //判断添加的Action
        if (action.equals(BluetoothDevice.ACTION_FOUND)) {
            //获取蓝牙设备
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (device != null) {
                addBluetoothDevice(device);
            }
        } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
            LogUtil.e("经典蓝牙", "扫描到设备数量:" + foundList.size());
            refreshLayout.finishRefresh();
        }
    }
};

 蓝牙搜索-低功耗蓝牙搜索步骤:

  1. 获取低功耗蓝牙适配器
  2. 检测蓝牙功能是否可用
  3. 搜索低功耗蓝牙
  4. 通过Android 5.0以上和Android 5.0以下低功耗蓝牙搜索回调,处理搜索结果

 低功耗蓝牙搜索实现关键代码:

//api 18及以上才拥有ble api
//获取低功耗蓝牙适配器
final BluetoothManager bluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
//设备的蓝牙功能打开是否可用
if (mBluetoothAdapter.enable()) {}

//扫描
//Android 5.0以上,扫描的结果在mScanCallback中进行处理
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    if (mBluetoothLeScanner == null) {
        mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
    }
    mBluetoothLeScanner.startScan(mScanCallback);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
    //Android 4.3以上,Android 5.0以下
    if (mBluetoothAdapter != null) {
        mBluetoothAdapter.startLeScan(mLeScanCallback);
    }
}

    /**
     * Android 5.0及以上 蓝牙设备扫描回调.
     */
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    public class MScanCallback extends ScanCallback {
        @Override
        public void onScanResult(int callbackType, final ScanResult result) {
//            LogUtil.e("BluetLe","设备信号:" + result.getRssi() + "ms");
            if (!bluetoothDeviceList.contains(result.getDevice())) {

                bluetoothDeviceList.add(result.getDevice());
                if (mOnScanLeDeviceListener != null) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            mOnScanLeDeviceListener.onScanDevice(result.getDevice());
                        }
                    });
                }
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
            LogUtil.e("BluetLe","扫描失败,错误代码:" + errorCode);
        }
    }

    /**
     * Android 4.3以上,Android 5.0以下 蓝牙设备扫描回调.
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public class MLeScanCallback implements BluetoothAdapter.LeScanCallback {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            if (device == null) {
                return;
            }
            if (!bluetoothDeviceList.contains(device)) {
                bluetoothDeviceList.add(device);
                if (mOnScanLeDeviceListener != null) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            mOnScanLeDeviceListener.onScanDevice(device);
                        }
                    });
                }
            }
        }
    }

蓝牙模块类型和蓝牙设备类型获取: 

    获取蓝牙设备的蓝牙类型
    int type = BluetoothDevice.getType()
    
    一下是BluetoothDevice.getType()的值
    /**
     * Bluetooth device type, Unknown(未知设备)
     */
    public static final int DEVICE_TYPE_UNKNOWN = 0;

    /**
     * Bluetooth device type, Classic - BR/EDR devices(传统蓝牙)
     */
    public static final int DEVICE_TYPE_CLASSIC = 1;

    /**
     * Bluetooth device type, Low Energy - LE-only(低功耗蓝牙BLE)
     */
    public static final int DEVICE_TYPE_LE = 2;

    /**
     * Bluetooth device type, Dual Mode - BR/EDR/LE(双模蓝牙)
     */
    public static final int DEVICE_TYPE_DUAL = 3;
    获取搜索到的蓝牙设备类型(一般通过getMajorDeviceClass()确定设备类型):
    int minor = BluetoothDevice.getBluetoothClass().getDeviceClass();//次要设备类组成
    int major = BluetoothDevice.getBluetoothClass().getMajorDeviceClass();//主要设备类


    /**
     * Defines all device class constants.
     * <p>Each {@link BluetoothClass} encodes exactly one device class, with
     * major and minor components.
     * <p>The constants in {@link
     * BluetoothClass.Device} represent a combination of major and minor
     * device components (the complete device class). The constants in {@link
     * BluetoothClass.Device.Major} represent only major device classes.
     * <p>See {@link BluetoothClass.Service} for service class constants.
     * 单独的说,一个设备只有一个设备类,设备类由主要设备类和次要设备类组成
     */
    public static class Device {
        private static final int BITMASK = 0x1FFC;


	/**
         * Defines all major device class constants.
         * <p>See {@link BluetoothClass.Device} for minor classes.
         */
        public static class Major {
            private static final int BITMASK = 0x1F00;//7936,位掩码

            public static final int MISC = 0x0000;//0,其他
            public static final int COMPUTER = 0x0100;//256,电脑
            public static final int PHONE = 0x0200;//512,手机
            public static final int NETWORKING = 0x0300;//768,联网
            public static final int AUDIO_VIDEO = 0x0400;//1024,音频视频
            public static final int PERIPHERAL = 0x0500;//1280,外围设备
            public static final int IMAGING = 0x0600;//1536,成像
            public static final int WEARABLE = 0x0700;//1792,可穿戴
            public static final int TOY = 0x0800;//2048,玩具
            public static final int HEALTH = 0x0900;//2304,健康
            public static final int UNCATEGORIZED = 0x1F00;//7936,未分类
        }

        // Devices in the COMPUTER major class(电脑)
        public static final int COMPUTER_UNCATEGORIZED = 0x0100;
        public static final int COMPUTER_DESKTOP = 0x0104;
        public static final int COMPUTER_SERVER = 0x0108;
        public static final int COMPUTER_LAPTOP = 0x010C;
        public static final int COMPUTER_HANDHELD_PC_PDA = 0x0110;
        public static final int COMPUTER_PALM_SIZE_PC_PDA = 0x0114;
        public static final int COMPUTER_WEARABLE = 0x0118;

        // Devices in the PHONE major class(手机)
        public static final int PHONE_UNCATEGORIZED = 0x0200;
        public static final int PHONE_CELLULAR = 0x0204;
        public static final int PHONE_CORDLESS = 0x0208;
        public static final int PHONE_SMART = 0x020C;
        public static final int PHONE_MODEM_OR_GATEWAY = 0x0210;
        public static final int PHONE_ISDN = 0x0214;

        // Minor classes for the AUDIO_VIDEO major class(音频视频)
        public static final int AUDIO_VIDEO_UNCATEGORIZED = 0x0400;
        public static final int AUDIO_VIDEO_WEARABLE_HEADSET = 0x0404;
        public static final int AUDIO_VIDEO_HANDSFREE = 0x0408;
        //public static final int AUDIO_VIDEO_RESERVED              = 0x040C;
        public static final int AUDIO_VIDEO_MICROPHONE = 0x0410;
        public static final int AUDIO_VIDEO_LOUDSPEAKER = 0x0414;
        public static final int AUDIO_VIDEO_HEADPHONES = 0x0418;
        public static final int AUDIO_VIDEO_PORTABLE_AUDIO = 0x041C;
        public static final int AUDIO_VIDEO_CAR_AUDIO = 0x0420;
        public static final int AUDIO_VIDEO_SET_TOP_BOX = 0x0424;
        public static final int AUDIO_VIDEO_HIFI_AUDIO = 0x0428;
        public static final int AUDIO_VIDEO_VCR = 0x042C;
        public static final int AUDIO_VIDEO_VIDEO_CAMERA = 0x0430;
        public static final int AUDIO_VIDEO_CAMCORDER = 0x0434;
        public static final int AUDIO_VIDEO_VIDEO_MONITOR = 0x0438;
        public static final int AUDIO_VIDEO_VIDEO_DISPLAY_AND_LOUDSPEAKER = 0x043C;
        public static final int AUDIO_VIDEO_VIDEO_CONFERENCING = 0x0440;
        //public static final int AUDIO_VIDEO_RESERVED              = 0x0444;
        public static final int AUDIO_VIDEO_VIDEO_GAMING_TOY = 0x0448;

        // Devices in the WEARABLE major class(可穿戴)
        public static final int WEARABLE_UNCATEGORIZED = 0x0700;
        public static final int WEARABLE_WRIST_WATCH = 0x0704;
        public static final int WEARABLE_PAGER = 0x0708;
        public static final int WEARABLE_JACKET = 0x070C;
        public static final int WEARABLE_HELMET = 0x0710;
        public static final int WEARABLE_GLASSES = 0x0714;

        // Devices in the TOY major class(玩具)
        public static final int TOY_UNCATEGORIZED = 0x0800;
        public static final int TOY_ROBOT = 0x0804;
        public static final int TOY_VEHICLE = 0x0808;
        public static final int TOY_DOLL_ACTION_FIGURE = 0x080C;
        public static final int TOY_CONTROLLER = 0x0810;
        public static final int TOY_GAME = 0x0814;

        // Devices in the HEALTH major class(健康)
        public static final int HEALTH_UNCATEGORIZED = 0x0900;
        public static final int HEALTH_BLOOD_PRESSURE = 0x0904;
        public static final int HEALTH_THERMOMETER = 0x0908;
        public static final int HEALTH_WEIGHING = 0x090C;
        public static final int HEALTH_GLUCOSE = 0x0910;
        public static final int HEALTH_PULSE_OXIMETER = 0x0914;
        public static final int HEALTH_PULSE_RATE = 0x0918;
        public static final int HEALTH_DATA_DISPLAY = 0x091C;

        // Devices in PERIPHERAL major class(外围设备)
        /**
         * @hide
         */
        public static final int PERIPHERAL_NON_KEYBOARD_NON_POINTING = 0x0500;
        /**
         * @hide
         */
        public static final int PERIPHERAL_KEYBOARD = 0x0540;
        /**
         * @hide
         */
        public static final int PERIPHERAL_POINTING = 0x0580;
        /**
         * @hide
         */
        public static final int PERIPHERAL_KEYBOARD_POINTING = 0x05C0;
    }

效果图:

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值