低功耗蓝牙的记录与总结

最近要去接触有蓝牙方面的项目,必须要掌握低功耗蓝牙的使用,于是乎就到处查资料,边看边操作,将自己查到的东西和学到的东西做一个记录;

编写配置方面要先去声明权限

<uses-permission android:name="android.permission.BLUETOOTH"/> 使用蓝牙所需要的权限
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> 使用扫描和设置蓝牙的权限(申明这一个权限必须申明上面一个权限)

一、蓝牙的初始化

1.获取BluetoothAdapter

 manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
 adapter = manager.getAdapter();

2.检测一些基础设置

是否支持低功耗蓝牙

蓝牙是否开启

private boolean check() {
        return (null != adapter && adapter.isEnabled());
}

如果没有开启就通过吐司提示用户开启或者是跳转到打开蓝牙的页面让用户去开启。

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

二、扫描蓝牙设备

(在整个扫描的过程中要使用同一个回调接口,所以需要定义一个回调接口供两个方法使用)

final BluetoothAdapter.LeScanCallback callback = new BluetoothAdapter.LeScanCallback() {

1.开始扫描

adapter.startLeScan(callback);

2.停止扫描

  adapter.stopLeScan(callback);

三、连接蓝牙设备

 mGatt = device.connectGatt(MainActivity.this, true, new BluetoothGattCallback() {
                    @Override
                    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                        super.onConnectionStateChange(gatt, status, newState);
                        if (newState == BluetoothProfile.STATE_CONNECTED) {
                            LogUtils.I("蓝牙连接");
                        }
                        if (newState == BluetoothProfile.STATE_CONNECTED) {
                            LogUtils.I("设备已经连接");
                        }
                    }

在上面的代码中可以看到如果newState==STATE_CENNECTED,那么就表示设备连接成功了

四、获取服务,调用以下方法

 mGatt.discoverServices();

在callback的回调中如果得知获取服务成功,那就表示两个蓝牙建立了可通讯的连接了

 @Override
                    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                        super.onServicesDiscovered(gatt, status);
                        LogUtils.I("调用了onServicesDiscovered");
                        if (status==BluetoothGatt.GATT_SUCCESS){
                            LogUtils.I("获取服务成功");
                        }else {
                            LogUtils.I("获取服务失败");
                        }
                    }

猜你喜欢

转载自blog.csdn.net/qq_40801158/article/details/81510852