Android 蓝牙4.0 BLE 获取链接设备Rssi值

来源:互联网 发布:下载天际通软件 编辑:程序博客网 时间:2024/05/21 11:04

   在网上查了很多资料,没有BLE获取RSSI值的资料,这几天弄了BLE 的Rssi值获取,写下来,做记录~

     蓝牙BLE 服务回调方法

// 通过BLE API的不同类型的回调方法@SuppressLint("NewApi")private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {// 当连接状态发生改变@Overridepublic 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.已经链接上GATT服务");// Attempts to discover services after successful connection.// 试图发现服务连接成功后。Log.i(TAG, "Attempting to start service discovery试图发现服务连接成功后。:"+ mBluetoothGatt.discoverServices());// 当设备无法连接} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {intentAction = ACTION_GATT_DISCONNECTED;mConnectionState = STATE_DISCONNECTED;close();Log.i(TAG, "Disconnected from GATT server.不能链接上GATT服务");broadcastUpdate(intentAction);}}// 发现新服务端@Overridepublic void onServicesDiscovered(BluetoothGatt gatt, int status) {if (status == BluetoothGatt.GATT_SUCCESS) {broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);} else {Log.w(TAG, "onServicesDiscovered received: " + status);}}// 读取特征值@Overridepublic void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status) {// TODO Auto-generated method stubsuper.onCharacteristicRead(gatt, characteristic, status);Log.d(TAG, "读到数据了的");if (status == BluetoothGatt.GATT_SUCCESS) {broadcastReadUpdate(ACTION_DATA_AVAILABLE, characteristic);}}// 写出特征值@Overridepublic void onCharacteristicWrite(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status) {// TODO Auto-generated method stubsuper.onCharacteristicWrite(gatt, characteristic, status);Log.d(TAG, "写出数据了~~");if (status == BluetoothGatt.GATT_SUCCESS) {broadcastWriteUpdate(ACTION_WRITE_DATA, characteristic);}}@Overridepublic void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {broadcastReadUpdate(ACTION_DATA_AVAILABLE, characteristic);}@Overridepublic void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {// TODO Auto-generated method stubsuper.onReadRemoteRssi(gatt, rssi, status);//将回调的RSSI值赋值BLERSSI=rssi;}};

重点是最后一个回调方法onReadRemoteRssi(),

//是否能读取到已连接设备的RSSI值//执行该方法一次,获得蓝牙回调onReadRemoteRssi()一次 /**      * Read the RSSI for a connected remote device.      * */    public boolean getRssiVal() {         if (mBluetoothGatt == null)             return false;         return mBluetoothGatt.readRemoteRssi();            } 

调用getRssiVal(),回调方法返回一次RSSi值。。。。。。

Demo http://download.csdn.net/detail/bruce60/8850593