ble藍芽技術
/**
*搜尋BLE終端
*
*/
public class BleManager{
private BluetoothManager bluetoothManager;
public static BluetoothAdapter mBluetoothAdapter;
public BleManager(Context mContext){
bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
}
/**
*藍芽狀態 - 模組
*/
/**
* 判斷是否支援藍芽
* @return
*/
public boolean isSupportBle(){
if(mBluetoothAdapter == null){
return false;
}
return true;
}
/**
* 得到藍芽當前狀態
* @return
*/
public boolean bleIsEnabled(){
Log.e("ble" , "ble.isEnabled() = " + mBluetoothAdapter.isEnabled());
return mBluetoothAdapter.isEnabled();
}
/**
* 開啟藍芽
*/
public void openBle(){
mBluetoothAdapter.enable();
}
/**
* 開啟藍芽 - 呼叫系統方法 - dialog顯示
*/
private void openBle() {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
/**
*藍芽掃描 模組
*/
1、開始掃描: mBluetoothAdapter.startLeScan(mLeScanCallback);
2、停止掃描:
mBluetoothAdapter.stopLeScan(mLeScanCallback)
3、ble掃描回撥:
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
}
}
/**
*藍芽繫結 模組
*/
/** 需複製BluetoothLeClass.java檔案至專案中 */
1、初始化BluetoothLeClass的物件
private BluetoothLeClass mBLE;
BluetoothGattCharacteristic MyAttCharacteristic;
/** * * 藍芽繫結模組初始化 */ private void initBlueToothLe(){ // 註冊Bluetooth adapter mBLE = new BluetoothLeClass(MainActivity.this); if (!mBLE.initialize()) { Log.e(TAG, "BLE Initialize"); finish(); } mBLE.setOnServiceDiscoverListener(mOnServiceDiscover); // 接收返回資料回撥 mBLE.setOnDataAvailableListener(mOnDataAvailable); }
private BluetoothLeClass.OnServiceDiscoverListener mOnServiceDiscover = new BluetoothLeClass.OnServiceDiscoverListener(){ @Override public void onServiceDiscover(BluetoothGatt gatt) { displayGattServices(mBLE.getSupportedGattServices()); } };
private void displayGattServices(List<BluetoothGattService> gattServices) { if (gattServices == null) return; for (BluetoothGattService gattService : gattServices) { //-----Service鐨勫瓧孌典俊鎭�-----// int type = gattService.getType(); Log.e(TAG,"-->service type:"+Utils.getServiceType(type)); Log.e(TAG,"-->includedServices size:"+gattService.getIncludedServices().size()); Log.e(TAG,"-->service uuid:"+gattService.getUuid()); //-----Characteristics鐨勫瓧孌典俊鎭�-----// List<BluetoothGattCharacteristic> gattCharacteristics =gattService.getCharacteristics(); for (final BluetoothGattCharacteristic gattCharacteristic: gattCharacteristics) { Log.e(TAG,"---->char uuid:"+gattCharacteristic.getUuid()); int permission = gattCharacteristic.getPermissions(); Log.e(TAG,"---->char permission:"+Utils.getCharPermission(permission)); int property = gattCharacteristic.getProperties(); Log.e(TAG,"---->char property:"+Utils.getCharPropertie(property)); byte[] data = gattCharacteristic.getValue(); if (data != null && data.length > 0) { Log.e(TAG,"---->char value:"+new String(data)); } //UUID_KEY_DATA鏄彲浠ヨ窡钃濈墮妯″潡涓插彛閫氫俊鐨凜haracteristic if(gattCharacteristic.getUuid().toString().equals(Utils.UUID_KEY_UART)) { //鎵懼埌涓插彛鏈嶅姟 MyAttCharacteristic = gattCharacteristic; //鎺ュ彈Characteristic琚啟鐨勯�氱煡,鏀跺埌钃濈墮妯″潡鐨勬暟鎹悗浼氳Е鍙憁OnDataAvailable.onCharacteristicWrite() mBLE.setCharacteristicNotification(gattCharacteristic, true); } //-----Descriptors鐨勫瓧孌典俊鎭�-----// List<BluetoothGattDescriptor> gattDescriptors = gattCharacteristic.getDescriptors(); for (BluetoothGattDescriptor gattDescriptor : gattDescriptors) { Log.e(TAG, "-------->desc uuid:" + gattDescriptor.getUuid()); int descPermission = gattDescriptor.getPermissions(); Log.e(TAG,"-------->desc permission:"+ Utils.getDescPermission(descPermission)); byte[] desData = gattDescriptor.getValue(); if (desData != null && desData.length > 0) { Log.e(TAG, "-------->desc value:"+ new String(desData)); } } } } }
/**
*ble裝置 - 斷開連線 模組
*/
1、ble手動斷開連線
mBLE.disconnect();
2、監聽ble自動斷開連線
// 寫在初始化方法
mBLE.setOnDisconnectListener(mOnDisConnect);
/** * 監聽ble裝置斷開 */ private BluetoothLeClass.OnDisconnectListener mOnDisConnect = new BluetoothLeClass.OnDisconnectListener() { @Override public void onDisconnect(BluetoothGatt gatt) { // 判斷獲取到斷開的ble裝置 是否 為 之前所繫結的ble裝置 if(gatt.getDevice().getName() != null && gatt.getDevice().getAddress().equals(bleConnectAddress) ){ recyHandler.obtainMessage(BLEDISCONNECTHANDLER , gatt.getDevice().getName()).sendToTarget(); Log.e("bleDisConnect" , "DeviceDisConnectName = "+gatt.getDevice().getName()); } } };
/**
*藍芽 - 傳送資料 模組
*/
1、傳送資料
private void sendCode(){
if(MyAttCharacteristic != null){
MyAttCharacteristic.setValue(sendByteCode);
mBLE.writeCharacteristic(MyAttCharacteristic);
}
}
2、接收資料回撥
// 寫在初始化方法裡
mBLE.setOnDataAvailableListener(mOnDataAvailable);
private BluetoothLeClass.OnDataAvailableListener mOnDataAvailable = new BluetoothLeClass.OnDataAvailableListener(){
/** * 接收返回指令 - read */@Overridepublic void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { String str = characteristic.getValue();Log.e(TAG, "onCharacteristicRead " + gatt.getDevice().getName() + " read "+ characteristic.getUuid().toString() + " -> "+ str);} /** * 接收返回指令 - write */@Overridepublic void onCharacteristicWrite(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {bytes_Rec = characteristic.getValue();Log.e(TAG,"onCharacteristicWrite "+gatt.getDevice().getName() +" write "+characteristic.getUuid().toString() +" -> "+bytes_Rec);} };
/**
*廣播監聽 - 藍芽狀態改變 模組
*/
BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { /** * 監聽藍芽的狀態改變 */ if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1); switch (state) { case BluetoothAdapter.STATE_ON: setToast(getResources().getString(R.string.bleIsOpen)); break; case BluetoothAdapter.STATE_OFF: setToast(getResources().getString(R.string.bleIsClose)); openBle(); break; case BluetoothAdapter.STATE_TURNING_ON: setToast(getResources().getString(R.string.bleIsOpening)); break; case BluetoothAdapter.STATE_TURNING_OFF: setToast(getResources().getString(R.string.bleIsClosing)); break; } } } };
/** * onDestroy */ @Override protected void onDestroy() { super.onDestroy(); if(sendCodeTimer != null){ sendCodeTimer.cancel(); } if( mBLE != null){ mBLE.close(); } unregisterReceiver(receiver); }
/**
*新增藍芽許可權 模組
*/
<!-- 關於藍芽許可權 --> <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/> <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
}