蓝牙Bluetooth(BLE)

来源:互联网 发布:表扬淘宝客服的话语 编辑:程序博客网 时间:2024/05/01 13:04

1、Bluetooth Low Energy 低电量消耗的蓝牙

2、4.3(18)以上支持

3、关键点及其概念:

1.Generic Attribute Profile (GATT) 用来规定通过BLE Link发送和接受数据片段的基础的准则,当前所有的低电量规则都是基于它;Bluetooth Special  Interest Group(SIG:蓝牙技术联盟)

2.Attribute Protocol (ATT)/(GATT/ATT) GATT是在其基础上建立起来的,是一种最优的传输,为了达到这个目的,用尽可能少的字节数,并且每一个  Attritbute被指定了一个UUID;Attritbute被格式化位Characteristic或者service来传输

3.Characteristic包含一个value和Descriptor,类似于Class

4.Descriptor用来描述Characteristic的value

5.Service 一组Characteristic的集合

4、使用BLE要遵守的准则

1.Central vs. peripheral. 中间的搜寻设备,外围的发送信号 

2.GATT server vs. GATT client 规定设备之间建立连接的规则(我的理解是谁发送消息谁是server ,谁接受消息谁是client 

5.  BLE Permissions

<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"/>//
通过设置android:required来决定是否‘只’支持BLE

同一时间只能搜索,BLE或者Classic中的一种类型的设备

6. 创建BLE

1.获取BluetoothAdapter

final BluetoothManager bluetoothManager =(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
//4.3以后支持这种方式

2.打开蓝牙

private BluetoothAdapter mBluetoothAdapter;
...
// Ensures Bluetooth is available on the device and it is enabled. If not,
// displays a dialog requesting user permission to enable Bluetooth.
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

7.查找BLE设备

由于查找是集中耗电过程所有要注意:查找到你想要的设备,立即停止查找;禁止循环查找,可以设置一个限制查找的时间

/**
 * Activity for scanning and displaying available BLE devices.
 */
public class DeviceScanActivity extends ListActivity {


    private BluetoothAdapter mBluetoothAdapter;
    private boolean mScanning;
    private Handler mHandler;


    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;
    ...
    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                }
            }, SCAN_PERIOD);


            mScanning = true;
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        ...
    }
...
}

如果你要加密可以调用startLeScan(UUID[], BluetoothAdapter.LeScanCallback)已UUID为适配码;


8.连接GATT服务

BluetoothGatt mBluetoothGatt = device.connectGatt( Context,在服务可用的情况下是否自动连接, BluetoothGattCallback);

9.读取BLE Attributes



0 0