DISTRIBUTION OF TIZEN-BASED WATCH APPS HAS BEEN DISCONTINUED

Use the Accessory SDK in Android

1. Declaring the Android Permission

To use the Accessory SDK, you must declare the following permission.

The following permission has to be specified in the AndroidManifest.xml file to use the Samsung Accessory Service:

<uses-permission android:name=
"com.samsung.accessory.permission.ACCESSORY_FRAMEWORK" />

2. Declaring the Broadcast Receiver

If the broadcast receiver is not added in the AndroidManifest.xml file, no intents handled by the Samsung Accessory Service Framework are delivered to your application.

<application>
	<receiver android:name="com.samsung.android.sdk.accessory.RegisterUponInstallReceiver">
		<intent-filter>
			<action android:name="com.samsung.accessory.action.REGISTER_AGENT" />
		</intent-filter>
	</receiver>
	<receiver android:name="com.samsung.android.sdk.accessory.ServiceConnectionIndicationBroadcastReceiver">
		<intent-filter>
			<action android:name="com.samsung.accessory.action.SERVICE_CONNECTION_REQUESTED" />
		</intent-filter>
	</receiver>
</application>

Communicating with the remote Peer Agent needs the declaration of a service in the AndroidManifest.xml. SAService can handle receiving request of service connections. When the tested devices are O OS or above, SAService should be running in foreground because of the background limitation. This ensures that the application is derived from the SAAgentV2 class.

<application>
	<service android:name="com.samsung.android.sdk.accessory.SAService" />
</application>

3. Defining the Accessory Service Profile

Communicating with a remote Peer Agent requires the declaration of descriptions about the Accessory Service Profile. This is declared in a separate file in the /res/xml folder in your application project. The path of the actual XML file can be added in the application’s AndroidManifest.xml file.

For example, /res/xml/.xml:

<application>
	<meta-data
		android:name="AccessoryServicesLocation"
		android:value="/res/xml/accessoryservices.xml" />
</application>

An example of the Accessory Service Profile XML file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<application name="MyApplication">
		<serviceProfile
				id="/org/example/myapp/my_message"
				name="myapplication"
				role="provider"
				serviceImpl="com.example.myapplication.ProviderService"
				version="1.0"
				serviceLimit="ANY"
				serviceTimeout="10">
			<supportedTransports>
				<transport type="TRANSPORT_BT" />
				<transport type="TRANSPORT_WIFI" />
			</supportedTransports>
			<serviceChannel
					id="110"
					dataRate="low"
					priority="low"
					reliability= "enable"/>
		</serviceProfile>
	</application>
</resources>

When the application is installed, the Samsung Accessory Service Framework automatically registers its Accessory Peer Agents using the information specified in your service profile XML file. Similarly, the Accessory Peer Agents are deregistered when the application is uninstalled. An error log is dumped if the registration process fails to register the Accessory Service Profile implementation. To define the Accessory Service Profile, see A.1 Validating Accessory Service Profile XML in this.

4.Finding Accessory Peer Agents

The service provider or service consumer application can search for matching Accessory Peer Agents by calling the SAAgentV2.findPeerAgents() method. Matching Accessory Peer Agents have the same Accessory Service Profile (such as Notification Service or Weather Service), and have a complementary provider or consumer relationship with the calling Accessory Peer Agent. Accessory Peer Agents with different Accessory Service Profiles for service providers or service consumers do not “match” and cannot be connected with each other. If 2 Accessory Peer Agents have the same Accessory Service Profile with different versions, however, they are still considered to “match”. For example, a Notification service consumer that implements the Notification Service Profile version 2.0 and a Notification service provider that implements the Notification Service Profile version 1.0 “match”.

The application searches for matching Peer Agents by calling the SAAgentV2.findPeerAgents() method. If a matching Peer Agent is found, the application is notified though the SAAgentV2.onFindPeerAgentResponse() method. If a matching Peer Agent is not found, the same callback is used, but the result has a null Peer Agent and the reason why no match was found.

@Override
protected void
onFindPeerAgentResponse(SAPeerAgent peerAgent, int result)
{
	if (result == PEER_AGENT_FOUND)
	{
	/* Peer Agent is found */
	}
	else if (result == FINDPEER_DEVICE_NOT_CONNECTED)
	{
	/* Peer Agents are not found, no accessory device connected */
	}
	else if(result == FINDPEER_SERVICE_NOT_FOUND )
	{
	/* No matching service on connected accessory */
	}
}

5. Setting up the Service Connection

If the application wants to establish a service connection with only one Accessory Peer Agent, check the first callback. You can also check the identity or properties of the discovered Accessory Peer Agents by calling the methods provided by the SAPeerAgent class to decide which Accessory Peer Agent you want to form a service connection with. The application can initiate a service connection with an Accessory Peer Agent by calling the SAAgentV2.requestServiceConnection() method.

This method is called from a worker thread. If you need to do any heavy lifting or long latency work in the callback, spawn a separate thread.

If a service provider connects only with a specific service consumer, or a service consumer with a specific service provider, the service provider and consumer are called ”companion applications”. When you only want to connect to a companion service provider or service consumer, call the methods provided by the SAPeerAgent class for specific information, such as model number or vendor information, before calling the SAAgentV2.requestServiceConnection() method. For example, when a photo printer service provider on an accessory device from a company only wants to connect to a photo printer service consumer on a smart device from the same company, they are companion applications.

The remote Accessory Peer Agent either accepts or rejects your service connection request. Your application is notified with the SAAgentV2.onServiceConnectionResponse() callback. The request can be accepted (and a service connection established) or rejected, or it can fail to establish the service connection for other reasons.

When a service connection is successfully established, the requesting Accessory Peer Agent gets an instance of the SASocket object, which is used to handle service connection events and send or receive data to and from Accessory Peer Agents.

private ProviderServiceConnection mConnectionHandler = null;

@Override
protected void
onServiceConnectionResponse(SAPeerAgent peerAgent, SASocket socket, int result)
{
	if (result == SAAgentV2.CONNECTION_SUCCESS)
	{
		if (socket != null)
		{
			mConnectionHandler = (ProviderServiceConnection) socket;
			Log.d(TAG, "Gear connection is successful.");
		}
	}
	else if (result == SAAgentV2.CONNECTION_ALREADY_EXIST)
	{
		Log.e(TAG, "Gear connection is already exist.");
	}
}

public class ProviderServiceConnection extends SASocket
{
}

6. Handling the Setup Service Connection Request

The service provider or consumer application is notified with the SAAgentV2.onServiceConnectionRequested() callback when a remote Accessory Peer Agent wants to create a service connection with it:

  • The Accessory Peer Agent implementation can accept or reject service connection requests by calling the acceptServiceConnectionRequest() or rejectServiceConnectionRequest() method.

  • The default implementation of the SAAgentV2.onServiceConnectionRequested() callback is to accept every incoming service connection request from any remote Accessory Peer Agent. Your Accessory Peer Agent implementation can override this method, usually to check the identity and properties of the requesting remote Accessory Peer Agent before accepting or rejecting incoming service connection requests.

  • The SAAgentV2.onServiceConnectionRequested() callback can check for Accessory Peer Agent-specific information before accepting service connection requests. You can use the SAPeerAgent object methods for checking specific information, such as application name or vendor ID.

If your application accepts the service connection request, your application is notified through the SAAgentV2.onServiceConnectionResponse() callback when the service connection is established or a failure occurs. On success, an SASocket object is passed with the callback. If you want to implement a service provider application that can serve multiple service consumer applications at the same time, keep a repository of the SASocket objects for all active service connections, and give an identifier for each SASocket object.

The SAAgentV2.onServiceConnectionResponse() callback is called from a worker thread. If you need to do any heavy lifting or long latency work in the callback, spawn a separate thread.

@Override
protected void
onServiceConnectionRequested(SAPeerAgent peerAgent)
{
	if (peerAgent != null)
	{
		acceptServiceConnectionRequest(peerAgent);
	}
}

@Override
protected void
onServiceConnectionResponse(SAPeerAgent peerAgent, SASocket socket, int result)
{
	if (result == SAAgentV2.CONNECTION_SUCCESS)
	{
		if (socket != null)
		{
			mConnectionHandler = (ProviderServiceConnection) socket;
			Log.d(TAG, "Gear connection is successful.");
		}
	}
	else if (result == SAAgentV2.CONNECTION_ALREADY_EXIST)
	{
		Log.e(TAG, "Gear connection is already exist.");
	}
}

7. Exchanging Data with the Accessory Peer Agent

Call the SASocket.send() method of the SASocket object (passed with the SAAgentV2.onServiceConnectionResponse() callback) to send data on the selected service channel inside an established service connection. The Samsung Accessory Service Framework provides a datagram service. Either all the data is sent or nothing is sent. The service connection encapsulates all service channels as defined by the Accessory Service Profile specification. Do not send a byte array bigger than that defined by the SAPeerAgent.getMaxAllowedDataSize() method, which returns the size limit that you can send to the remote Accessory Peer Agent. The limit is a variable that depends on the transport type and memory size of the remote accessory device.

public void
sendMessage(final String message)
{
	if (mConnectionHandler != null)
	{
		new Thread(new Runnable()
		{
			public void run()
			{
			try
			{
				mConnectionHandler.send(CHANNEL_ID, message.getBytes());
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
			}
		}).start();
	}
}

If you want your data encrypted, call the SASocket.secureSend() method instead of send().

public class ProviderServiceConnection extends SASocket
{
	@Override
	public void onReceive(int channelId, byte[ ] data)
		{
			if (mConnectionHandler == null)
			{
				return;
			}
			final String message = new String(data);
			if (mProviderServiceListener != null && !mProviderServiceListener.isActivityHidden())
			{
				mProviderServiceListener.onReceiveMessage(message);
			}
			else
			{
				mHandler.post(new Runnable()
				{
				@Override
				public void run()
				{
					Toast.makeText(getBaseContext(), message, Toast.LENGTH_SHORT).show();
					try
					{
						mConnectionHandler.send(CHANNEL_ID, "Android app is sleeping".getBytes());
					}
					catch (IOException e)
					{
						e.printStackTrace();
					}
				}
			});
		}
	}
}