最新在项目中接触到蓝牙BLE设备,参考了一下官方文档,使用官方API可以使用4.0协议很简单的和设备进行通信,下面就把经验分享一下,本人主要涉及蓝牙功能开启,设备搜索,两个设备之间的通信,首先想使用蓝牙4.0协议调试设备必须是Android4.3以上,由于智能电视本身蓝牙功能就是开启的,所以本文省略掉开启蓝牙的介绍,大家有兴趣可以看一下官方API。首先是访问蓝牙需要的权限mantifest注册如下:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
使用GATT协议核心类官方文档介绍如下:
Get the BluetoothAdapter
The BluetoothAdapter
is required for any and all Bluetooth activity. The BluetoothAdapter
represents the device's own Bluetooth adapter (the Bluetooth radio). There's one Bluetooth adapter for the entire system, and your application can interact with it using this object. The snippet below shows how to get the adapter. Note that this approach uses getSystemService()
to return an instance of BluetoothManager
, which is then used to get the adapter. Android 4.3 (API Level 18) introduces BluetoothManager
:
private BluetoothAdapter mBluetoothAdapter; ... // Initializes Bluetooth adapter. final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter();
查找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); } ... } ... }
If you want to scan for only specific types of peripherals, you can instead call startLeScan(UUID[], BluetoothAdapter.LeScanCallback)
, providing an array of