Mohsen
Mohsen

Reputation: 85

How To Send And Receive An Object In Nearby Connections Api

Google In Documentations Saying:

you can exchange data by sending and receiving Payload objects. A Payload can represent a simple byte array, such as a short text message; a file, such as a photo or video; or a stream, such as the audio stream from the device's microphone.

But I Wonder How Send And Receive Complex Data Types Such As An Object.

Upvotes: 0

Views: 1175

Answers (2)

Nícolas Schirmer
Nícolas Schirmer

Reputation: 1444

You can use an Serializer helper to (de)serialize an Object.

/** Helper class to serialize and deserialize an Object to byte[] and vice-versa **/
public class SerializationHelper {   
    public static byte[] serialize(Object object) throws IOException{
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        // transform object to stream and then to a byte array
        objectOutputStream.writeObject(object);
        objectOutputStream.flush();
        objectOutputStream.close();
        return byteArrayOutputStream.toByteArray();
    }

    public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException{
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        return objectInputStream.readObject();
    }
}

On your activity you can call

@Override
protected void onReceive(Endpoint endpoint, Payload payload) {
    try{
        onDataReceived(endpoint, SerializationHelper.deserialize(payload.asBytes()));
    } catch (IOException | ClassNotFoundException e) { e.getMessage(); }
}

protected void onDataReceived(Endpoint endpoint, Object object){
   // do something with your Object
}

public void sendDataToAllDevices(Object object){
    try {
         send(Payload.fromBytes(SerializationHelper.serialize(object)));
    } catch (IOException e) { e.getMessage(); }
}

Upvotes: 2

Xlythe
Xlythe

Reputation: 2033

You'll need to serialize your Object into bytes, send it as a BYTE Payload, and then deserialize it on the other end. There are a lot of ways to do this in Java, but as a starter, look into Serializable (https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html) and/or Protobuf (https://developers.google.com/protocol-buffers/).

Upvotes: 1

Related Questions