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"/>



}

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