How to send more than 20 bytes data over ble in android?

后端 未结 4 521
终归单人心
终归单人心 2020-12-16 23:15

I am trying to send more than 33 bytes using simple loops, Is anybody has idea how to send more than 20 bytes data over android ble.

if(!mConnected) return;
         


        
4条回答
  •  伪装坚强ぢ
    2020-12-16 23:55

    Instead of using sleep for every chunk, i just found a better and efficient way for my application to send more than 20 bit data.

    The packets will be send after onCharacteristicWrite() triggered. i just found out this method will be triggered automatically after peripheral device (BluetoothGattServer) sends a sendResponse() method.

    firstly we have to transform the packet data into chunk with this function:

    public void sendData(byte [] data){
        int chunksize = 20; //20 byte chunk
        packetSize = (int) Math.ceil( data.length / (double)chunksize); //make this variable public so we can access it on the other function
    
        //this is use as header, so peripheral device know ho much packet will be received.
        characteristicData.setValue(packetSize.toString().getBytes());
        mGatt.writeCharacteristic(characteristicData);
        mGatt.executeReliableWrite();
    
        packets = new byte[packetSize][chunksize];
        packetInteration =0;
        Integer start = 0;
        for(int i = 0; i < packets.length; i++) {
            int end = start+chunksize;
            if(end>data.length){end = data.length;}
            packets[i] = Arrays.copyOfRange(data,start, end);
            start += chunksize;
        }
    

    after our data ready, so i put my iteration on this function:

    @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            if(packetInteration

提交回复
热议问题