Nearby API Post-Connection Phase

We have already discussed near pre-connection phase in our previous blog.
Check this reference : http://blogs.innovationm.com/nearby-api-pre-connection-phase/

Now, in this blog, we will have a look at the post-connection phase.

After the connection between advertiser and discoverer is made successfully, post-connection phase starts.
In the post-connection phase, there is no distinction between advertiser and discoverer.
Both can send data to each other.
Sharing of data happens in the form of Payload objects.

Types of Payload :

1. Bytes
These are the simplest types of payloads.
If you want to send simple data like messages or metadata(data about data) then it must be your choice.
For creating a BYTE payload, you need to call Payload.fromBytes(byte[] bytes), where bytes is a byte array with a maximum size of Connections.MAX_BYTES_DATA_SIZE.

To retrieve BYTE payload on the receiving side, you need to call payload.asBytes() which will return the byte array.

2. File
If you want to share a file stored on your local device such as a photo or video then you should send them as a File payload.
For creating a FILE payload, you need to call Payload.fromFile() by passing either a java.io.File or a ParcelFileDescriptor as the parameter.

To retrieve FILE payload on the receiving side, you need to call payload.asFile().asJavaFile() or payload.asFile().asParcelFileDescriptor().

3. Stream
In case you want to send a large amount of data such as an audio stream then Stream payloads would be the right choice.
For creating a FILE payload, you need to call Payload.fromStream() by passing in either an InputStream or a ParcelFileDescriptor as the parameter.

To retrieve FILE payload on the receiving side, you need to call payload.asStream().asInputStream() or payload.asStream().asParcelFileDescriptor().

Sending and Receiving

In order to send payloads to a conneted endpoint, you need to call sendPayload() method.

In order to receive payloads, you need to implement onPayloadReceived() method.
onPayloadReceived() method is one of the two methods of PayloadCallback class.
An instance of this class is passed on both sides, while accepting connection, in acceptConnection() method.
As soon as any one of the two(advertiser and discoverer) receives the very first byte of the incoming payload, a callback is triggered in onPayloadReceived() method.

Payload Progress Update

The second method of PayloadCallback class is onPayloadTransferUpdate() which updates us about the progress of both incoming and outgoing payloads.
That means, this method receives a callback on both sending and receiving sides.

When the payload is transferred completely, onPayloadTransferUpdate() is called with a status of PayloadTransferUpdate.Status.SUCCESS.

 

Leave a Reply