Shared Spaces on Android
Android shared spaces are implemented using delegates and callbacks. All requests are asynchronous.
There are a couple of different ways to create a shared space, depending on how you want to get started. Choose from any of the following methods:
1. Invite a peer to a new shared space and populate the initial data.
2. Invite a peer to a new shared space and request the peer populate the initial data.
3. Create an empty shared space and allow peers to request invitations (or join).
1. Invite a peer to a new shared space and populate the initial data.
a. Create a delegate class
Create a subclass of CanIOSharedSpaceDelegate
and implement the following (empty for now) methods:
public class MySharedSpaceDelegate implements CanIOSharedSpaceDelegate {
@Override
public void onCreateSpace(CanIOSharedSpace sharedSpace) { }
@Override
public void onInvitationAccepted(CanIOSharedSpace sharedSpace, CanIOPeer peer) { }
@Override
public void onInvitationRejected(CanIOSharedSpace sharedSpace, CanIOPeer peer) { }
@Override
public void onObjectAdded(CanIOSharedSpace sharedSpace, CanIOSharedSpaceObject sharedObject) { }
@Override
public void onObjectUpdated(CanIOSharedSpace sharedSpace, CanIOSharedSpaceObject sharedObject) { }
@Override
public void onObjectRemoved(CanIOSharedSpace sharedSpace, String key) { }
}
This delegate class will be called when various events occur in the Shared Space.
b. Create the space with your delegate (the invitation is sent after the space is created)
Find the place in your code where you want to create the space and invite a peer. We will create a new instance of the delegate object and create the space. Note that we don't invite the peer. We want to populate the initial data before inviting the peer so that the peer receives the request and has the space object to start working with immediately.
CanIOPeer peerToInvite = ...;
MySharedSpaceDelegate mySharedSpaceDelegate = new MySharedSpaceDelegate(new Handler() {
@Override
public void handleMessage(Message msg) {
CanIOSharedSpace sharedSpace = msg.getData().getParcelable("space");
sharedSpace.invitePeer(peerToInvite);
}
});
final CanIOSharedSpace mySharedSpace = CanIO.getManager().createSharedSpace(mySharedSpaceDelegate);
To make this work, we need to modify the MySharedSpaceDelegate
a little to support the new Handler
added:
public class MySharedSpaceDelegate implements CanIOSharedSpaceDelegate {
private Handler mOnCreateSpaceHandler;
public MySharedSpaceDelegate(Handler onCreateSpaceHandler) {
mOnCreateSpaceHandler = onCreateSpaceHandler;
}
@Override
public void onCreateSpace(CanIOSharedSpace sharedSpace) {
if (mOnCreateSpaceHandler != null) {
Message msg = new Message();
Bundle b = new Bundle();
b.putParcelable("space", sharedSpace);
msg.setData(b);
mOnCreateSpaceHandler.sendMessage(msg);
}
}
... // the rest can stay unchanged for now