Android 蓝牙4.0实现,自动匹配蓝牙设备

本文介绍了如何使用Android蓝牙4.0实现与蓝牙设备的自动匹配和数据交换。首先检查设备是否支持蓝牙4.0并打开蓝牙,接着搜索蓝牙设备并建立连接,然后详细阐述了连接过程、数据读写以及监听特征值变化的方法。最后提到了在项目中遇到的蓝牙配对和数据分包发送的问题及其解决方案。
摘要由CSDN通过智能技术生成

        今天开始写博客来记录我的工作学习成长,作为一个初学者,近期的一个工作是通过Android蓝牙4.0来实现与蓝牙设备的数据交换,下面就通过代码和文字来解释一下整个过程。

        首先我要说明的是,我再项目中使用了一个开源库,我觉得不错,所有代码都是在该库基础上实现的,地址:https://github.com/litesuits/android-lite-bluetoothLE

下面进入正题

1,检查设备是否支持蓝牙4.0,和打开蓝牙

if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "设备不支持BLE", Toast.LENGTH_SHORT).show();
            finish();
        }
 
// Ensures Bluetooth is enabled on the device.  If Bluetooth is not currently enabled,
        // fire an intent to display a dialog asking the user to grant permission to enable it.
        if (!mBluetoothAdapter.isEnabled()) {
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }

2,搜索蓝牙4.0设备,该方法是搜索蓝牙设备SCAN_PERIOD事件,通过回调函数new PeriodScanCallback来处理结果,分为超时和找到蓝牙设备,自己可以在回调函数中作相应处理

 /**
    * scan devices for a while
    */
   private void scanDevicesPeriod() {
   
    mScanning = true;
    this.startBluetoothProgressDialog("正在搜索蓝牙设备...");
    showMessage.setText("正在搜索蓝牙设备...");
       SampleGattAttributes.liteBluetooth.startLeScan(new PeriodScanCallback(SCAN_PERIOD) {
           @Override
           public void onScanTimeout() {
            BluetoothSearchActivity.this.stopBluetoothProgressDialog();
            mScanning = false;
handler1.sendEmptyMessage(3);
SampleGattAttributes.liteBluetooth.stopScan(null);
           }


           @Override
           public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            if(device != null && device.getName() != null && device.getName().startsWith("XXXX")){
bluetoothDevice = device;
deviceName.add(device.getName()); 
mDeviceName = device.getName();
mDeviceAddress = device.getAddress();
SampleGattAttributes.address

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值