如何在附近的连接A​​pi中发送和接收对象

时间:2017-10-01 17:33:24

标签: android google-nearby

Google In Documentations Saying:

  

您可以通过发送和接收Payload对象来交换数据。 Payload可以表示简单的字节数组,例如短文本消息;文件,例如照片或视频;或流,例如来自设备麦克风的音频流。

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

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

在您的活动中,您可以致电

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