Interact with the Application on the Android Device
1. Create a service connection.
Connecting to the first available peer found:
try {
var agent = await Samsung.Sap.Agent.GetAgent(Samsung.Sap.Service.Profiles.First());
var peers = await agent.FindPeers(null);
if (peers.Count() == 0)
{
Console.WriteLine("There are no peers to connect to.");
}
else
{
var peer = peers.First();
await peer.Connection.Open();
peer.Connection.Send(agent.Channels.First().Value, System.Text.Encoding.ASCII.GetBytes("Hello"));
}
} except (Exception exc) {
Console.WriteLine("Communication failure: " + exc.Message);
}
Handling of an incomming connection:
Samsung.Sap.Agent agent = null;
agent = await Samsung.Sap.Agent.GetAgent("/my/profile", onConnect: con =>
{
if (con.Peer.ProfileVersion == agent.ProfileVersion)
{
con.DataReceived += (s, e) => {
Console.WriteLine($"Received {e.Data.Length} bytes from {e.Peer.DeviceName}/{e.Channel.ID}");
};
return true; // accept connection from peers with the same profile version as ours
}
else
{
return false; // reject other connections
}
});
2. Disconnect the service.
Connection between Peers can be closed by calling Connection.Close() method.
connection.Close();
3. Send a message.
In this sample text message is sent using Peer.SendMessage(). In contrast to sending data using Connection.Send() method establishing connection between Peers is not required.
await peer.SendMessage(Encoding.UTF8.GetBytes("Hello Message"));
4. Receive a message.
Receiving message from remote Peer is handled by OnMessage callback set before.
private async void OnMessage(Peer peer, byte[] content)
{
string message = Encoding.UTF8.GetString(content) + " Time: " + DateTime.Now.ToShortTimeString();
Toast.DisplayText(message);
await peer.SendMessage(Encoding.UTF8.GetBytes(message));
}
In this case, app replies to a receiving command from remote Accessory Peer Agent in Smart device by providing the current time stamp.