[Sony Smartwatch] kpbird:
In previous two articles I covered development environment setup and anatomy of SmartWatch. This article will contain deep dive into coding with simple Hello Word example.

http://xdaforums.com/smartwatch/sony/tut-introduction-smart-watch-t2807896

http://xdaforums.com/smartwatch/sony/tut-smartwatch-app-development-part-2-t2807954

This demo will cover Notification API only. We will develop a single Android project named "Hello SmartWatch" which acts as a Host application and Extension application both. It means I will use single codebase for both things. Hello SmartWatch project has an Activity to send and clear notification to SmartWatch.

I assume that you have already imported SmartExtensionAPI and SmartExtensionUtils libraries in workspace.

Let's jump to the code.

List of Classes and purpose

MainActivity.java: It is use to generate and clear notification.

HelloExtensionReceiver.java: It receives input event generated by SmartWatch and forward control to the Extension Service.

HelloExtensionService.java: core logic of Host application needs to be written in ExtensionService. It is also responsible to register a host application to SmartWatch.

HelloRegistrationInformation.java: It provides essential information to register host application and API requirement.

This demo application contains only above four classes but actual application may have more classes. In above classes MainActivity acts as a Smart Extension application and rest of classes acts as a Host application.

Step 1: Create new Android project in eclipse named "HelloSmartWatch".

Step 2: Let's create UI first. Open activity_main.xml and put two EditText box for Title and Message respectively and two buttons for Send and Clear notification respectively.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="Send Notification"
android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
android:id="@+id/etTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Title" >
</EditText>

<EditText
android:id="@+id/etMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Message" >
</EditText>

<Button
android:id="@+id/btnSend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="buttonClicked"
android:text="Send Notification" />

<Button
android:id="@+id/btnClearn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="buttonClicked"
android:text="Clear Notification" />

</LinearLayout>

Step 3: Let's make button alive by writing action in MainActivity.java. I am using onClick property of buttons, so I don't require to find object of button and setOnClickListener. I can write code in "buttonClicked" method which is defined. When a user click on "Send Notification" button I am simply firing ExtensionService with INTENT_ACTION_ADD action and other required data and same for "Clear Notification" but with INTENT_ACTION_CLEAR action.

package com.kpbird.hellosmartwatch;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

}

public void buttonClicked(View v){
if(v.getId() == R.id.btnSend){
Intent serviceIntent = new Intent(this, HelloExtensionService.class);
serviceIntent.setAction(HelloExtensionService.INTENT_ACTION_ADD);
EditText etName = (EditText) findViewById(R.id.etTitle);
EditText etMsg = (EditText) findViewById(R.id.etMessage);
serviceIntent.putExtra("name", etName.getText().toString());
serviceIntent.putExtra("message", etMsg.getText().toString());
startService(serviceIntent);
}
else if(v.getId() == R.id.btnClearn){
Intent serviceIntent = new Intent(this, HelloExtensionService.class);
serviceIntent.setAction(HelloExtensionService.INTENT_ACTION_CLEAR);
startService(serviceIntent);
}

}
}

Step 4: Create HelloExtensionReceiver.java, It extends BroadcastReceiver. It works as bridge between SmartWatch and Host application, It will receive event generated in SmartWatch and forward it to HelloExtensionService.java

package com.kpbird.hellosmartwatch;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class HelloExtensionReceiver extends BroadcastReceiver{

private String TAG = this.getClass().getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "HelloExtensionReceiver onReceiver: " + intent.getAction());
intent.setClass(context, HelloExtensionService.class);
context.startService(intent);
}

}

Step 5: Create HelloRegistrationInformation.java and extends with RegistrationInformation class. As the name suggests, It will use to register host application in Smart Connect. It has six methods that we need to override, among these four methods are used to declare required APIs and two methods used for extension registration and source registration. You can have multiple sources in a host application.

package com.kpbird.hellosmartwatch;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;

import com.sonyericsson.extras.liveware.aef.notification.Notification;
import com.sonyericsson.extras.liveware.aef.registration.Registration;
import com.sonyericsson.extras.liveware.extension.util.ExtensionUtils;
import com.sonyericsson.extras.liveware.extension.util.registration.RegistrationInformation;

public class HelloRegistrationInformation extends RegistrationInformation{
private Context mContext;
public HelloRegistrationInformation(Context ctx){
if (ctx == null) {
throw new IllegalArgumentException("context == null");
}
mContext = ctx;
}
@Override
public int getRequiredNotificationApiVersion() {
return 1;
}
@Override
public int getRequiredWidgetApiVersion() {
return 0;
}

@Override
public int getRequiredControlApiVersion() {
return 0;
}

@Override
public int getRequiredSensorApiVersion() {
return 0;
}

@Override
public ContentValues getExtensionRegistrationConfiguration() {
String extensionIcon = ExtensionUtils.getUriString(mContext,R.drawable.ic_launcher);
String iconHostapp = ExtensionUtils.getUriString(mContext,R.drawable.ic_launcher);
String extensionIcon48 = ExtensionUtils.getUriString(mContext,R.drawable.ic_launcher_48);

String configurationText = "Hello SmartWatch";
String extensionName = "Hello SmartWatch";

ContentValues values = new ContentValues();
values.put(Registration.ExtensionColumns.CONFIGURATION_ACTIVITY,MainActivity.class.getName());
values.put(Registration.ExtensionColumns.CONFIGURATION_TEXT, configurationText);
values.put(Registration.ExtensionColumns.EXTENSION_ICON_URI, extensionIcon);
values.put(Registration.ExtensionColumns.EXTENSION_48PX_ICON_URI, extensionIcon48);

values.put(Registration.ExtensionColumns.EXTENSION_KEY,HelloExtensionService.EXTENSION_KEY);
values.put(Registration.ExtensionColumns.HOST_APP_ICON_URI, iconHostapp);
values.put(Registration.ExtensionColumns.NAME, extensionName);
values.put(Registration.ExtensionColumns.NOTIFICATION_API_VERSION,getRequiredNotificationApiVersion());
values.put(Registration.ExtensionColumns.PACKAGE_NAME, mContext.getPackageName());
return values;
}

@Override
public ContentValues[] getSourceRegistrationConfigurations() {

ContentValues sourceValues = null;

String iconSource1 = ExtensionUtils.getUriString(mContext,R.drawable.ic_launcher_30);
String iconSource2 = ExtensionUtils.getUriString(mContext,R.drawable.ic_launcher_18);
String iconBw = ExtensionUtils.getUriString(mContext,R.drawable.ic_launcher_18_bw);
String textToSpeech = "Notification from Hello SmartWatch Application";
sourceValues = new ContentValues();
sourceValues.put(Notification.SourceColumns.ENABLED, true);
sourceValues.put(Notification.SourceColumns.ICON_URI_1, iconSource1);
sourceValues.put(Notification.SourceColumns.ICON_URI_2, iconSource2);
sourceValues.put(Notification.SourceColumns.ICON_URI_BLACK_WHITE, iconBw);
sourceValues.put(Notification.SourceColumns.UPDATE_TIME, System.currentTimeMillis());
sourceValues.put(Notification.SourceColumns.NAME, mContext.getString(R.string.app_name));
sourceValues.put(Notification.SourceColumns.EXTENSION_SPECIFIC_ID, HelloExtensionService.EXTENSION_SPECIFIC_ID);
sourceValues.put(Notification.SourceColumns.PACKAGE_NAME, mContext.getPackageName());
sourceValues.put(Notification.SourceColumns.TEXT_TO_SPEECH, textToSpeech);
sourceValues.put(Notification.SourceColumns.ACTION_1,"Hello");
sourceValues.put(Notification.SourceColumns.ACTION_ICON_1,ExtensionUtils.getUriString(mContext, R.drawable.ic_launcher));

List<ContentValues> bulkValues = new ArrayList<ContentValues>();
bulkValues.add(sourceValues);
return bulkValues.toArray(new ContentValues[bulkValues.size()]);
}

}

Step 6: Create HelloExtensionService.java and extends with ExtensionService. It will contain main logic of SmartWatch host application. We need to implement two abstract methods named "getRegistrationInformation()", which sends object of HelloRegistrationInformation class and "keepRunningWhenConnected()",return true if you want to keep ExtensionService running as long as SmartWatch is connected with Smart Phone. For notification example we need to create two methods named "addData" and "clearData". It will generate and clear notification in SmartWatch respectively. We also need to implement onStartCommand to interact with Service.

package com.kpbird.hellosmartwatch;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.util.Log;
import android.widget.Toast;

import com.sonyericsson.extras.liveware.aef.notification.Notification;
import com.sonyericsson.extras.liveware.aef.registration.Registration;
import com.sonyericsson.extras.liveware.extension.util.ExtensionService;
import com.sonyericsson.extras.liveware.extension.util.ExtensionUtils;
import com.sonyericsson.extras.liveware.extension.util.notification.NotificationUtil;
import com.sonyericsson.extras.liveware.extension.util.registration.DeviceInfoHelper;
import com.sonyericsson.extras.liveware.extension.util.registration.RegistrationInformation;

public class HelloExtensionService extends ExtensionService {

public static final String EXTENSION_SPECIFIC_ID = "EXTENSION_SPECIFIC_ID_HELLO_NOTIFICATION";
public static final String EXTENSION_KEY = "com.kpbird.hellosmartwatch.key";
public static final String INTENT_ACTION_ADD = "com.kpbird.hellosmartwatch.action.add";
public static final String INTENT_ACTION_CLEAR = "com.kpbird.hellosmartwatch.action.clear";

private String TAG = this.getClass().getSimpleName();
public HelloExtensionService() {
super(EXTENSION_KEY);
Log.i(TAG, "Constructor");
}

@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate()");
}

@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy()");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int retVal = super.onStartCommand(intent, flags, startId);
if (intent != null) {
if (INTENT_ACTION_CLEAR.equals(intent.getAction())) {
Log.d(TAG, "onStart action: INTENT_ACTION_CLEAR");
clearData(intent);
stopSelfCheck();
} else if (INTENT_ACTION_ADD.equals(intent.getAction())) {
Log.d(TAG, "onStart action: INTENT_ACTION_ADD");
addData(intent);
stopSelfCheck();
}
}

return retVal;
}

@Override
protected RegistrationInformation getRegistrationInformation() {
return new HelloRegistrationInformation(this);
}

@Override
protected boolean keepRunningWhenConnected() {
return false;
}

private void clearData(Intent intent) {
NotificationUtil.deleteAllEvents(this);
}

private void addData(Intent intent) {
String name = "Name";
String message = "Message";
if (intent.getExtras().containsKey("name"))
name = intent.getExtras().getString("name");
if (intent.getExtras().containsKey("message"))
message = intent.getExtras().getString("message");

long time = System.currentTimeMillis();
long sourceId = NotificationUtil.getSourceId(this,
EXTENSION_SPECIFIC_ID);
Log.i(TAG, "Source ID :" + sourceId);
if (sourceId == NotificationUtil.INVALID_ID) {
Log.e(TAG, "Failed to insert data");
return;
}
String profileImage = ExtensionUtils.getUriString(this,R.drawable.ic_launcher);

ContentValues eventValues = new ContentValues();
eventValues.put(Notification.EventColumns.EVENT_READ_STATUS, false);
eventValues.put(Notification.EventColumns.DISPLAY_NAME, name);
eventValues.put(Notification.EventColumns.MESSAGE, message);
eventValues.put(Notification.EventColumns.PERSONAL, 1);
eventValues.put(Notification.EventColumns.PROFILE_IMAGE_URI,profileImage);
eventValues.put(Notification.EventColumns.PUBLISHED_TIME, time);
eventValues.put(Notification.EventColumns.SOURCE_ID, sourceId);

try {
getContentResolver().insert(Notification.Event.URI, eventValues);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Failed to insert event", e);
} catch (SecurityException e) {
Log.e(TAG,
"Failed to insert event, is Live Ware Manager installed?",
e);
} catch (SQLException e) {
Log.e(TAG, "Failed to insert event", e);
}
}

@Override
protected void onViewEvent(Intent intent) {
String action = intent.getStringExtra(Notification.Intents.EXTRA_ACTION);
Log.i(TAG, "Action : " + action);
String hostAppPackageName = intent.getStringExtra(Registration.Intents.EXTRA_AHA_PACKAGE_NAME);
Log.i(TAG, "HostAppPackageName: " + hostAppPackageName);
boolean advancedFeaturesSupported = DeviceInfoHelper.isSmartWatch2ApiAndScreenDetected(this, hostAppPackageName);
Log.i(TAG, "Advanced Features Supported: " + advancedFeaturesSupported);
int eventId = intent.getIntExtra(Notification.Intents.EXTRA_EVENT_ID,-1);
try {
Cursor cursor = getContentResolver().query(Notification.Event.URI,null, Notification.EventColumns._ID + " = " + eventId,null, null);
if (cursor != null && cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex(Notification.EventColumns.DISPLAY_NAME));
String message = cursor.getString(cursor.getColumnIndex(Notification.EventColumns.MESSAGE));
Toast.makeText(this,"Notification: Name: " + name + " Message: " + message,Toast.LENGTH_LONG).show();
Log.i(TAG, "Name: " + name);
Log.i(TAG, "Message: "+ message);
}
cursor.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}

@Override
public void onRegisterResult(boolean success) {
super.onRegisterResult(success);
Log.d(TAG, "onRegisterResult :" + success);
}

}

Step 7: Finally we need to register HelloExtensionReceiver and HelloExtensionService in AndroidManifest.xml like following. We also need to provide user permission "EXTENSION_PERMISSION".

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kpbird.hellosmartwatch"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="16" />
<uses-permission android:name="com.sonyericsson.extras.liveware.aef.EXTENSION_PERMISSION" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.kpbird.hellosmartwatch.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".HelloExtensionService" />

<receiver
android:name=".HelloExtensionReceiver"
android:permission="com.sonyericsson.extras.liveware.aef.HOSTAPP_PERMISSION" >
<intent-filter>

<!-- Generic extension intents. -->
<action android:name="com.sonyericsson.extras.liveware.aef.registration.EXTENSION_REGISTER_REQUEST" />
<action android:name="com.sonyericsson.extras.liveware.aef.registration.ACCESSORY_CONNECTION" />
<action android:name="android.intent.action.LOCALE_CHANGED" />

<!-- Notification intents -->
<action android:name="com.sonyericsson.extras.liveware.aef.notification.VIEW_EVENT_DETAIL" />
<action android:name="com.sonyericsson.extras.liveware.aef.notification.REFRESH_REQUEST" />

<!-- Widget intents -->
<action android:name="com.sonyericsson.extras.aef.widget.START_REFRESH_IMAGE_REQUEST" />
<action android:name="com.sonyericsson.extras.aef.widget.STOP_REFRESH_IMAGE_REQUEST" />
<action android:name="com.sonyericsson.extras.aef.widget.ONTOUCH" />
<action android:name="com.sonyericsson.extras.liveware.extension.util.widget.scheduled.refresh" />

<!-- Control intents -->
<action android:name="com.sonyericsson.extras.aef.control.START" />
<action android:name="com.sonyericsson.extras.aef.control.STOP" />
<action android:name="com.sonyericsson.extras.aef.control.PAUSE" />
<action android:name="com.sonyericsson.extras.aef.control.RESUME" />
<action android:name="com.sonyericsson.extras.aef.control.ERROR" />
<action android:name="com.sonyericsson.extras.aef.control.KEY_EVENT" />
<action android:name="com.sonyericsson.extras.aef.control.TOUCH_EVENT" />
<action android:name="com.sonyericsson.extras.aef.control.SWIPE_EVENT" />
</intent-filter>
</receiver>
</application>
</manifest>

Step 8: Connect your SmartPhone and run this example. It will display MainActivity. Before jumping to "Send Notification", open Accessory Emulator and select Extension to verify that our HelloExtension is installed or not. Click on extension menu and it will display the registration details. If extension gets registered successfully then you can go back to Hello SmartWatch application and play with Send and Clear Notification functionality.

Screen Shots

[IMG="Open Accessory emulator and select SmartWatch 2, Wait for few second if Extensions and Notification API will not enable"]http://2.bp.blogspot.com/-qmkgQsMXmlk/UrQkJWhwjWI/AAAAAAAAErA/PcH8ZoKKm3A/s400/1.png[/IMG]

[IMG="Select Extensions"]http://4.bp.blogspot.com/-SKllSLoUvOE/UrQkKk8MXhI/AAAAAAAAErg/LmfkOywcWIs/s400/2.png[/IMG]

[IMG="You can see extension detail"]http://1.bp.blogspot.com/-r0k7Mq_Cd8A/UrQkKlXiEFI/AAAAAAAAErU/52L2Xo7CWUY/s400/3.png[/IMG]

[IMG="Click on "Show Extension Settings" will open this screen because at time of extension registration we provide MainActivity.java as Setting screen"]http://4.bp.blogspot.com/-uOI58aGJD9A/UrQkKhPaznI/AAAAAAAAErc/WRx1bn8tXng/s400/4.png[/IMG]

[IMG="Type Notification title and message and click Send Notification"]http://4.bp.blogspot.com/-EkWxs4WopX8/UrQkLZCBaFI/AAAAAAAAEsE/aHJ3F8FbuIA/s400/5.png[/IMG]

[IMG="Go back to Accessory emulator and select Notification API"]http://3.bp.blogspot.com/-Cf50vYHsDy0/UrQkLmZZOOI/AAAAAAAAErs/bo4Y_7sQ788/s400/6.png[/IMG]

[IMG="Select source, This will come from HelloRegistrationInformation's getSourceInformation function, It will display multiple option in the list if you have register multiple sources."]http://1.bp.blogspot.com/-MqMl_Pcl1R8/UrQkLqHKbRI/AAAAAAAAEr0/2NSEMVlD2hQ/s400/7.png[/IMG]

[IMG="Now, you can see the notification title which we just send"]http://1.bp.blogspot.com/-fHQ5sWfZ2Ak/UrQkMbVR_DI/AAAAAAAAEr4/zK_hM_qiqYw/s400/8.png[/IMG]

[IMG="click on menu button ":" will open action menu, you can add maximum 4 action, In our case we have implemented only one action"]http://4.bp.blogspot.com/-HZZzmLRFRio/UrQkMpkoAbI/AAAAAAAAEsI/O5l7z5tTG-4/s400/9.png[/IMG]

[IMG="Click on action menu will call onViewEvent method in HelloExtensionService.java. You can write any action in this method. In our example we just display Toast."]http://1.bp.blogspot.com/-bJmib0fKsxU/UrQkJYy4NXI/AAAAAAAAErI/MO63PEXhv2A/s400/10.png[/IMG]

[IMG="When you click on "Clear Notification" from HelloActivity and come back to emulator, you will see the effect"]http://3.bp.blogspot.com/-JpNw91T2wfY/UrQkJS79eJI/AAAAAAAAErE/OsFdrO03eOA/s400/11.png[/IMG]

Download Source Code​

Note: 1. Import project in eclipse 2. Make sure that you change SmartExtensionUtils and SmartExtensionAPI path from project properties.