当前位置: 移动技术网 > 移动技术>移动开发>Android > Android BLE定位应用(蓝牙搜索方法)

Android BLE定位应用(蓝牙搜索方法)

2020年08月11日  | 移动技术网移动技术  | 我要评论

最近刚好有一个需求,需要实时收取并保存指定蓝牙广播,用于蓝牙定位应用。

然后我使用老方法注册广播开启蓝牙搜素,发现并不能实时收到广播,有时会隔个几秒。

这个当然是不行的,蓝牙定位最低要求也是需要一秒一次。并且我手上的蓝牙板子,是每300毫秒就发送一次广播的。

在网上找了很多资料,一直没有实现。最近突然发现一个方法可以,好了废话不多说,直接上代码。

1.首先权限配置

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

2.  6.0以上记得动态权限

if (Build.VERSION.SDK_INT >= 23) {
    int checkAccessFinePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
    if (checkAccessFinePermission != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                1);
        Log.e(getPackageName(), "没有权限,请求权限");
        return;
    }
    Log.e(getPackageName(), "已有定位权限");
}

3. 初始化蓝牙BLE

BluetoothAdapter mBluetoothAdapter;
  BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }

4.开启搜索

private void toSearch() {
 
    if (mBluetoothAdapter.isDiscovering()) {
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
    }
    mBluetoothAdapter.startLeScan(mLeScanCallback);
}

5.监听回调

 private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi,
                                     byte[] scanRecord) {              
                    if (device.getAddress().equals("59:47:18:41:00:07")) {//比较MAC
                    Log.e("LeScanCallback","BluetoothAdapter.LeScanCallback    mac: "+device.getAddress());
                   
                    }
                }
            };

6. 操作上述步骤,你会发现搜索速度快的飞起,并且是一直在搜素,不像老的方法只能12秒(我记得是)后就不在搜索。

本文地址:https://blog.csdn.net/weixin_37592723/article/details/107904426

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网