如何在附近的连接中发送和接收对象 Api

How To Send And Receive An Object In Nearby Connections Api

Google 在文档中说:

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.

但我想知道如何发送和接收对象等复杂数据类型。

您需要将对象序列化为字节,将其作为 BYTE 负载发送,然后在另一端反序列化。在 Java 中有很多方法可以做到这一点,但作为初学者,请查看 Serializable (https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html) and/or Protobuf (https://developers.google.com/protocol-buffers/).

您可以使用序列化器助手来(反)序列化对象。

/** 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();
    }
}

在你的 activity 上你可以打电话给

@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(); }
}