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
         */
@Override public 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 */ @Override public 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"/>



}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章