1. 程式人生 > >Android Bluetooth 藍芽4.0 詳解

Android Bluetooth 藍芽4.0 詳解

本文介紹Android ble 藍芽4.0,也就是說API level >= 18,且支援藍芽4.0的手機才可以使用,如果手機系統版本API level < 18,也是用不了藍芽4.0的哦。

一、瞭解api及概念

1.1 BluetoothGatt

繼承BluetoothProfile,通過BluetoothGatt可以連線裝置(connect),發現服務(discoverServices),並把相應地屬性返回到 BluetoothGattCallback

1.2 BluetoothGattCharacteristic

相當於一個數據型別,它包括一個value和0~n個value的描述(BluetoothGattDescriptor)

1.3 BluetoothGattDescriptor

描述符,對Characteristic的描述,包括範圍、計量單位等

1.4 BluetoothGattService

服務,Characteristic的集合。

1.5 BluetoothProfile

一個通用的規範,按照這個規範來收發資料。

1.6 BluetoothManager

通過BluetoothManager來獲取BluetoothAdapter

1 BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

1.7 BluetoothAdapter

一個Android系統只有一個BluetoothAdapter ,通過BluetoothManager 獲取

1 BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();

1.8 BluetoothGattCallback

已經連線上裝置,對裝置的某些操作後返回的結果。這裡必須提醒下,已經連線上裝置後的才可以返回,沒有返回的認真看看有沒有連線上裝置。

1 2 3 4 5 6 7

private BluetoothGattCallback GattCallback = 

new BluetoothGattCallback() {

public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState){};

public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status){};

}; BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

BluetoothGatt gatt = device.connectGatt( this false , mGattCallback);

1.8.1:notification對應 onCharacteristicChanged 

1

gatt.setCharacteristicNotification(characteristic, true );

1.8.2:  onCharacteristicRead;

1 gatt.readCharacteristic(characteristic);

1.8.3:   onCharacteristicWrite;

1 gatt.wirteCharacteristic(mCurrentcharacteristic);

1.8.4:連線藍芽或者斷開藍芽 對應  onConnectionStateChange;

1.8.5:   onDescriptorRead;

1.8.6: writeDescriptor 對應 onDescriptorWrite;

1 gatt.writeDescriptor(descriptor);

1.8.7: readRemoteRssi 對應 onReadRemoteRssi;

1 gatt.readRemoteRssi()

1.8.8: executeReliableWrite 對應 onReliableWriteCompleted;

1.8.9: discoverServices 對應 onServicesDiscovered。

1 gatt.discoverServices()

1.9 BluetoothDevice

掃描後發現可連線的裝置,獲取已經連線的裝置

二、開啟藍芽許可權

1 2 3

<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.hardware.bluetooth_le設定為false,可以安裝在不支援的裝置上使用,判斷是否支援藍芽4.0用以下程式碼就可以了

1 2 3 4

if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {

Toast.makeText( this "裝置不支援藍芽4.0" , Toast.LENGTH_SHORT).show();

finish();

}

三、對藍芽的啟動關閉操作

1、利用系統預設開啟藍芽對話方塊

1 2 3 4

if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

}

2、後臺開啟藍芽,不做任何提示,這個也可以用來自定義開啟藍芽對話方塊啦

1 mBluetoothAdapter.enable();

3、後臺關閉藍芽

1 mBluetoothAdapter.disable();

四、掃描裝置,連線裝置,獲取裝置資訊 ,斷開連線裝置,自行檢視官方demo,還是看demo比較清晰啊