Working with BLE Android 4.3 how to write characteristics? Working with BLE Android 4.3 how to write characteristics? android android

Working with BLE Android 4.3 how to write characteristics?


The following code is write characteristic using byte[] data:

    public boolean writeCharacteristic(){    //check mBluetoothGatt is available    if (mBluetoothGatt == null) {        Log.e(TAG, "lost connection");        return false;    }    BluetoothGattService Service = mBluetoothGatt.getService(your Services);    if (Service == null) {        Log.e(TAG, "service not found!");        return false;    }    BluetoothGattCharacteristic charac = Service            .getCharacteristic(your characteristic);    if (charac == null) {        Log.e(TAG, "char not found!");        return false;    }    byte[] value = new byte[1];    value[0] = (byte) (21 & 0xFF);    charac.setValue(value);    boolean status = mBluetoothGatt.writeCharacteristic(charac);    return status;}


Please note that the logic OR in:
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0)" in the original post should be a logic AND for the permission check to work. Same for the second charaProp comparison. Otherwise bot statements are true regardless of the actual permission flag.


The following code is write characteristic using string data in utf-8 format:

public void writeCharacteristic(BluetoothGattCharacteristic characteristic,            String data) {        if (mBluetoothAdapter == null || mBluetoothGatt == null) {            Log.w(TAG, "BluetoothAdapter not initialized");            return;        }        Log.i(TAG, "characteristic " + characteristic.toString());        try {            Log.i(TAG, "data " + URLEncoder.encode(data, "utf-8"));            characteristic.setValue(URLEncoder.encode(data, "utf-8"));            // TODO            mBluetoothGatt.writeCharacteristic(characteristic);        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }    }

Hope it helps!