Android 4.3(API Level 18)介紹了內置平臺支持藍牙低能量的核心做用,並提供了API,應用程序能夠用它來發現設備,查詢服務,和讀寫字符。與傳統的藍牙相比,Bluetooth Low Energy (BLE) 旨在提供顯著下降功耗。這使得Android應用可以與具備BLE的低耗能設備進行通訊,例如,傳感器、心率監視器,健身設備,等等。 BLE 權限 爲了在應用程序中使用藍牙功能,必須聲明藍牙藍牙許可。您須要這個權限執行任何藍牙通訊,如請求鏈接,接受鏈接,傳輸數據。 聲明藍牙權限須要在應用的manifest 文件中加以下代碼: <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> 若是你想聲明應用程序僅BLE-capable設備可用,在你的應用程序的清單包括如下: <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/> 然而,若是你想讓你的應用程序可用的設備不支持BLE,你應該仍是這個元素包含在您的應用程序的清單,但在運行時設置android:required=「false」。在運行時您能夠決定BLE可用性經過使用PackageManager.hasSystemFeature(): //用這個檢查設備是否支持BLE。 if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show(); finish(); } 設置BLE BLE在您的應用程序能夠交互以前,你須要確認在設備上是支持BLE,若是是這樣,確保啓用。注意這檢查須要設置< uses-feature…/ >爲false。 若是不支持BLE,那麼你應該禁用任何BLE特性。若是支持,可是已經禁用,你能夠用你的應用啓動它。完成這個設置須要兩步,使用BluetoothAdapter。 1.獲取luetoothAdapter。 BluetoothAdapter表明設備的藍牙適配器。整個系統有一個藍牙適配器,和您的應用程序可使用這個對象與它交互。下面的代碼片斷顯示瞭如何獲取適配器。使用getSystemService ()返回一個BluetoothManager實例,而後獲取適配器。 Android 4.3(API LEVEL 18)引入了BluetoothManager: //初始化藍牙適配器 final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); 2.啓動藍牙 接下來,您須要確保啓用藍牙。用isEnabled()檢查藍牙當前是否啓動。若是這個方法返回false,那麼藍牙是關閉的。下面的代碼片斷檢查是否啓用藍牙。若是沒有,將提示用戶去設置啓用藍牙。 if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } 搜索藍牙設備 搜索藍牙設備使用startLeScan()方法。該方法以BluetoothAdapter.LeScanCallback做爲參數,您必須實現這個回調,由於這是如何返回掃描結果。由於掃描很是耗電,你應該遵照以下規則: · 只要找到了設備就應該中止搜索。 · 不要在一個無限循環中搜索, 須要設置一個時間限制搜索. 下面代碼做用是如何開始和結束搜索: 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對象數組,指定藍牙服務應用程序所支持的。 這裏使用BluetoothAdapter.LeScanCallback的實現用來顯示藍牙掃描結果: private LeDeviceListAdapter mLeDeviceListAdapter; ... // Device scan callback. private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) { runOnUiThread(new Runnable() { @Override public void run() { mLeDeviceListAdapter.addDevice(device); mLeDeviceListAdapter.notifyDataSetChanged(); } }); } }; 注意:不能在同一時間掃描BLE和傳統的藍牙。 連接 GATT Server 與BLE設備交互的第一步是鏈接到它,更具體地說,鏈接到設備上的GATT服務器。鏈接到GATT服務器使用connectGatt()方法,這個方法取三個參數:一個上下文對象,(布爾指示是否自動鏈接到設備就可用),和BluetoothGattCallback回調函數。 mBluetoothGatt = device.connectGatt(this, false, mGattCallback); 這個鏈接到GATT服務端經過BLE設備,並返回一個BluetoothGatt實例,而後您可使用GATT客戶端進行操做。調用者(Android應用程序)是GATT客戶端。BluetoothGattCallback用於提供結果給客戶端,如鏈接狀態,以及任何進一步的GATT客戶端操做。 在這個例子中,有幸得到應用程序提供了一個活動(DeviceControlActivity)鏈接,顯示數據,並顯示GATT服務和支持的設備特徵。基於用戶輸入,此活動與一個服務交互稱爲BluetoothLeService,這服務與BLE設備交互是經過Android BLE API: public class BluetoothLeService extends Service { private final static String TAG = BluetoothLeService.class.getSimpleName(); private BluetoothManager mBluetoothManager; private BluetoothAdapter mBluetoothAdapter; private String mBluetoothDeviceAddress; private BluetoothGatt mBluetoothGatt; private int mConnectionState = STATE_DISCONNECTED; private static final int STATE_DISCONNECTED = 0; private static final int STATE_CONNECTING = 1; private static final int STATE_CONNECTED = 2; public final static String ACTION_GATT_CONNECTED = "com.example.bluetooth.le.ACTION_GATT_CONNECTED"; public final static String ACTION_GATT_DISCONNECTED = "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED"; public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED"; public final static String ACTION_DATA_AVAILABLE = "com.example.bluetooth.le.ACTION_DATA_AVAILABLE"; public final static String EXTRA_DATA = "com.example.bluetooth.le.EXTRA_DATA"; public final static UUID UUID_HEART_RATE_MEASUREMENT = UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT); // Various callback methods defined by the BLE API. private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { String intentAction; if (newState == BluetoothProfile.STATE_CONNECTED) { intentAction = ACTION_GATT_CONNECTED; mConnectionState = STATE_CONNECTED; broadcastUpdate(intentAction); Log.i(TAG, "Connected to GATT server."); Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices()); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { intentAction = ACTION_GATT_DISCONNECTED; mConnectionState = STATE_DISCONNECTED; Log.i(TAG, "Disconnected from GATT server."); broadcastUpdate(intentAction); } } @Override // New services discovered public void onServicesDiscovered(BluetoothGatt gatt, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED); } else { Log.w(TAG, "onServicesDiscovered received: " + status); } } @Override // Result of a characteristic read operation public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic); } } ... }; ... } 當一個特定的回調函數被觸發,它調用適當的broadcastUpdate()輔助方法並將其傳遞一個action。注意,本節中的數據解析執行按照藍牙心率測量概要文件規範: private void broadcastUpdate(final String action) { final Intent intent = new Intent(action); sendBroadcast(intent); } private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) { final Intent intent = new Intent(action); // This is special handling for the Heart Rate Measurement profile. Data // parsing is carried out as per profile specifications. if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) { int flag = characteristic.getProperties(); int format = -1; if ((flag & 0x01) != 0) { format = BluetoothGattCharacteristic.FORMAT_UINT16; Log.d(TAG, "Heart rate format UINT16."); } else { format = BluetoothGattCharacteristic.FORMAT_UINT8; Log.d(TAG, "Heart rate format UINT8."); } final int heartRate = characteristic.getIntValue(format, 1); Log.d(TAG, String.format("Received heart rate: %d", heartRate)); intent.putExtra(EXTRA_DATA, String.valueOf(heartRate)); } else { // For all other profiles, writes the data formatted in HEX. final byte[] data = characteristic.getValue(); if (data != null && data.length > 0) { final StringBuilder stringBuilder = new StringBuilder(data.length); for(byte byteChar : data) stringBuilder.append(String.format("%02X ", byteChar)); intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString()); } } sendBroadcast(intent); } Back in DeviceControlActivity, these events are handled by a BroadcastReceiver: // Handles various events fired by the Service. // ACTION_GATT_CONNECTED: connected to a GATT server. // ACTION_GATT_DISCONNECTED: disconnected from a GATT server. // ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services. // ACTION_DATA_AVAILABLE: received data from the device. This can be a // result of read or notification operations. private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) { mConnected = true; updateConnectionState(R.string.connected); invalidateOptionsMenu(); } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) { mConnected = false; updateConnectionState(R.string.disconnected); invalidateOptionsMenu(); clearUI(); } else if (BluetoothLeService. ACTION_GATT_SERVICES_DISCOVERED.equals(action)) { // Show all the supported services and characteristics on the // user interface. displayGattServices(mBluetoothLeService.getSupportedGattServices()); } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) { displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA)); } } }; 閱讀BLE屬性 一旦你的Android應用程序鏈接到一個GATT服務器和發現服務,它能夠讀取和寫入屬性。例如,這段代碼遍歷服務器的服務和數據並將它們顯示在UI中: public class DeviceControlActivity extends Activity { ... // Demonstrates how to iterate through the supported GATT // Services/Characteristics. // In this sample, we populate the data structure that is bound to the // ExpandableListView on the UI. private void displayGattServices(List<BluetoothGattService> gattServices) { if (gattServices == null) return; String uuid = null; String unknownServiceString = getResources(). getString(R.string.unknown_service); String unknownCharaString = getResources(). getString(R.string.unknown_characteristic); ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>(); ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList<ArrayList<HashMap<String, String>>>(); mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>(); // Loops through available GATT Services. for (BluetoothGattService gattService : gattServices) { HashMap<String, String> currentServiceData = new HashMap<String, String>(); uuid = gattService.getUuid().toString(); currentServiceData.put( LIST_NAME, SampleGattAttributes. lookup(uuid, unknownServiceString)); currentServiceData.put(LIST_UUID, uuid); gattServiceData.add(currentServiceData); ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<HashMap<String, String>>(); List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics(); ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<BluetoothGattCharacteristic>(); // Loops through available Characteristics. for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) { charas.add(gattCharacteristic); HashMap<String, String> currentCharaData = new HashMap<String, String>(); uuid = gattCharacteristic.getUuid().toString(); currentCharaData.put( LIST_NAME, SampleGattAttributes.lookup(uuid, unknownCharaString)); currentCharaData.put(LIST_UUID, uuid); gattCharacteristicGroupData.add(currentCharaData); } mGattCharacteristics.add(charas); gattCharacteristicData.add(gattCharacteristicGroupData); } ... } ... } 接收GATT通知 當一個特定的設備上的特徵變化須要BLE的應用通知。這個代碼片斷顯示瞭如何設置一個通知特性,使用setCharacteristicNotification()方法: private BluetoothGatt mBluetoothGatt; BluetoothGattCharacteristic characteristic; boolean enabled; ... mBluetoothGatt.setCharacteristicNotification(characteristic, enabled); ... BluetoothGattDescriptor descriptor = characteristic.getDescriptor( UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG)); descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); mBluetoothGatt.writeDescriptor(descriptor); 一旦通知做爲一個特性被啓用,若是遠程設備上的特性變化將觸發onCharacteristicChanged()回調。 @Override // Characteristic notification public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic); } 關閉客戶端應用 一旦應用程序完成使用BLE設備,應該調用close()方法去釋放系統資源。 public void close() { if (mBluetoothGatt == null) { return; } mBluetoothGatt.close(); mBluetoothGatt = null; }