蓝牙4.0 BLE 入门
1. 手机需要android 4.3 及以上版本
2. 权限:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
只允许支持BLE 的手机安装还需要添加uses-feature
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
3. BLE 设备扫描
3.1 获取蓝牙适配器: mBluetoothAdapter = bluetoothManager.getAdapter();
3.2 开始扫描: mBluetoothAdapter.startLeScan(mLeScanCallback);
在调用扫描时, 需要实现LeScanCallback 回调接口, 用于扫描结果的返回:
protected LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) { Log.d(TAG, "find device -> "+ device.getName()+"mac:"+device.getAddress()); runOnUiThread(new Runnable() { public void run() { String mac = device.getAddress(); String name = device.getName(); // deviceAdapter.addDevice(new BluetoothItem(name, mac)); deviceAdapter.addDevice(new BluetoothItem(name, mac, rssi)); deviceAdapter.notifyDataSetChanged(); } }); } };3.3 获取扫描结果后,可以通过得到的设备地址, 来对设备进行连接, 连接上将得到一个BluetoothGatt 用于操作, 其中需要实现BluetoothGattCallback 回调, 其用于结果的返回, 如连接的状态,以及后面的读写等操作
final BluetoothDevice device = mBluetoothAdapter .getRemoteDevice(address); if (device == null) { Log.w(TAG, "Device not found. Unable to connect."); return false; } // We want to directly connect to the device, so we are setting the // autoConnect // parameter to false. mBluetoothGatt = device.connectGatt(this, true, mGattCallback);mGattCallback 回调函数:
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (newState == BluetoothProfile.STATE_CONNECTED) { broadcastUpdate(ACTION_GATT_CONNECTED); Log.i(TAG, "Connected to GATT server."); // Attempts to discover services after successful connection. Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices()); isConnectd = true; } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { Log.i(TAG, "Disconnected from GATT server."); isConnectd = false; broadcastUpdate(ACTION_GATT_DISCONNECTED, gatt.getDevice().getAddress()); } } //...略 }
在连接上蓝牙后, 通过调用 mBluetoothGatt.discoverServices(), 来发现蓝牙设备中的服务, 接下来就可以获取到设备中的服务列表 mBluetoothGatt.getServices(); 或者通过uuid 来获取某一个服务 BluetoothGattService gattService = mBluetoothGatt.getService(uuid);
服务中, 获得Characteristic 集合则调用 gattService.getCharacteristics();
在 Characteristic中, 可以通过 mBluetoothGatt.readCharacteristic(characteristic); 来读取其里面的数据, 其结果在mGattCallback 回调函数中获取.
写如数据: characteristic.setValue(data);
mBluetoothGatt.wirteCharacteristic(mCurrentcharacteristic);
4. 关闭连接 mBluetoothGatt.close();
原文:http://blog.csdn.net/xhalone/article/details/38537871