- A beginner guide to Android Watch App (From scratch to publish)
- Companion
- Step 1: Add wear Module
- Learning 1: Give same package name as your Phone module.
- Learning 1.2: Sign with the same certificate. The Identity of apps is same when they have identical package name and same signing certificate.
- Step 2: Add a launcher Activity
- Step3 : Finding Your main app
- In Watch
- In Phone
- Step 4 : Communication
- Step 5 : Publishing
- Summary
- How To Develop an Android Wear Application
- The Android Wear Platform
- Usage Patterns
- Design Philosophy
- Development Details
- Notifications
- Wearable Applications
- Connection and Data Exchange
- Example In Action
- Custom UI and Voice Actions
- Conclusion
A beginner guide to Android Watch App (From scratch to publish)
Have you ever struggled with how to develop an Android wear app OR you want to learn basics of Android watch app? In either case, You are at right place.
As usual, whenever Android does something new, it does not do justice to documentation. Recently we released an Android watch companion app for one of our appa and it was not a smooth experience. This article aims to cover the basics you need to know to develop a watch app. At the end of this article, you should be able to write a companion watch app. If you have experience in watch app, feel free to correct mistakes. I would appreciate notes.
Note: Android phone app development knowledge is required for this article.
Companion
I used companion word twice already and this is the third time. What is it? You can divide the Android watch app in 2 categories.
Standalone and Companion app. Former is when your app is a full-fledged app on watch and does not need a supportive app on Phone, an example can be weather app.
Latter is when you need your other app to run on the phone, an example can be smart lights app where all heavy lifting is done at phone and watch app is just to send command. Below is a screenshot for companion watch app for smart lights.
Android wear 2.0 is almost identical to you in terms of development with some restrictions of API’s not available and form factor of watch screen size.
In this article, we will discuss and learn about companion app for your existing Android app. The main app is running on phone and watch app is an add-on. We will discuss A-Z steps from development to publishing.
Step 1: Add wear Module
In Android studio, add a new module. Select the Android wear module.
Learning 1: Give same package name as your Phone module.
This sounds silly but we wasted a good amount of time because of this. Android studio by default neither offers this nor suggests this. For standalone watch apps, it does not matter as they do not depend on phone counterpart. But for a companion app, because it needs to interact with phone module and vice-versa, the identity has to be same on phone and watch. That’s how system offers security for apps to communicate.
Learning 1.2: Sign with the same certificate. The Identity of apps is same when they have identical package name and same signing certificate.
If you have signingConfig blocks in main app build file, you should use same certificates for watch module. I would recommend having identical signing block.
Add minimum target to 25 as Android wear 2.0 is available to watches with minimum Android 7
Step 2: Add a launcher Activity
You can run your watch module (check build file, it has configuration apply plugin: ‘com.android.application’), Android studio will allow you to run and it is exactly same as running an app on phone.
Tip: You can extend WearableActivity which offers utility functions ambient mode entered and exited. Consider ambient mode as a configuration change you handle in phone app (keyboard, orientation). In the watch, ambient mode triggers quite frequently and you should give it a thought whether it makes sense for you to do anything or not.
Add Launcher entry in Manifest and rest everything is same as Phone.
Step3 : Finding Your main app
Now your launcher activity is running, it is time to interact with your main app. I think Android has done a good job in that. As connected devices are increasing in number and form-factor, Android wear considers itself a mesh network of nodes where one Node is your phone. Your phone is no different for wear API.
Instead of finding the connected phone, you should find a node which has the capability of fulfilling your request. It may sound little confusing now but don’t worry, You will find it very easy once you understand.
Assume a user has 2 watches (one sport and one normal), one connected ring, one newly launched watch connected to two phones at a time and some new hardware in Android wear eco-system. Now your main app is running on one of the phone and user installed your wear app on one watch.
Android calls all these devices nodes.
Now Android came up with a decent solution. Instead of you querying all nodes(devices) and finding which has your app installed. Wear API offers a utility to do so.
It means you can expose a string literal which acts as a unique identifier when wear API will find your app in nodes mesh. Simplifying more, your app module on different devices can expose some offerings (capability in Android wear term) for e.g Your phone app module can say I am “watch-server” and watch module can say I am “watch-client”. You can use the same API on both devices, watch and phone. All you need to do is use different capability.
In Watch
Note that: These CAPABILITY_PHONE_APP and CAPABILITY_WATCH_APP are string literal defined by you.
Now question is how your module registers these offerings(capabilities) with system. IMHO they should have done with some Manifest tag pointing to some xml resource. However they chose to do it with only xml resource. You need to add one xml file wear.xml in your values folder. Example:
In Phone
You can choose any literal name which makes sense in your context. Once you have added wear.xml file, used same package name and signed with same certificate. You should be able to find the Node which offers desired capability.
Note that this will work if the user has an old version of your app on any node. Your search will not find the node with the desired capability and you can show an error message to the user to update the app.
Complete search Node code:
Same code in the watch with different literal CAPABILITY_PHONE_APP
Step 4 : Communication
Now you have found nodes, all you need is some sort of communication mechanism. Message Client is perfect API for you. It is very simple:
With this simple API, you can send any message to the node you just discovered in step 3. NodeId you will get from the Node. uniqueIdentifierOfMessage is your defined some string literal you will use to identify what message means. Example:
Data is the raw data you can send both ways. It is in the form of bytes, so you need to convert a string to byte and vice-versa.
We just sent a message, where was it received? By default, It is lost unless you add a listener. So in both apps, you should have the addListener line before anything.
This is where you will get the message you sent in the messageEvent form.
Message event also contains node of the sender so you can respond
Overall it feels like client-server model where both parties act as client and server time to time. I hope it is clear to you how to develop a watch app.
Step 5 : Publishing
This section is for people who have a play-store developer account. Others can skip.
I personally find publishing watch app little confusing. For those who have play store developer account, under release. They have an option of add from the library which did not work for me. I ended up using multi-apk approach. I had to generate watch apk with increased version code over my market app and publish normally.
It seems because of the manifest, Android play store is intelligent to serve APK to watch devices only.
Do not forget to add this in your manifest:
Summary
We saw Android is improving day by day and their decision of not hardcoding watch and considering everything Node is confusing at first but makes a lot of sense once you grasp the concept. There can be many devices/nodes connected at a time, few of them will have your app, few will not. Few will have an old version and few will have version mismatch and so on. To mitigate all this, we used capability client which can be used to search for Nodes who are offering those capabilities. For any node, all they need to add one wear.xml file with string array of `android_wear_capabilities` and system will take care of rest.
Once your node is found, you can interact with nodes using Message client which is very simple API to use. It is similar to a client-server model where each message has path and data associated with it.
Источник
How To Develop an Android Wear Application
Android Wear from Google is a Platform that connects your Android phone to your wrist. Since its release earlier this year, Android Wear has garnered a lot of attention, both from a consumer angle and also from developers, who want to ensure that they understand and have their applications ready to take advantage of a new way in which users will be interacting with contextual information.
This article will give a brief introduction to Android Wear and then jump into the platform vis-a-vis the developer.
Android Wear aims to provide just the right amount of information to the user at the right time. Keeping that theme in mind, Google has published design guidelines to help developers focus their thinking in terms of Android Wear applications. We will cover that in brief, as well as examine what it takes to get started with the Android Wear development environment and what APIs are available today to help Android developers ready their apps ready for the Wear platform.
The Android Wear Platform
Android Wear is an open operating system for wearable devices. It comes with a new User Interface —the result of Google working to understand how we use our phones today and how we can be more in touch with our environment. For example, data suggests that, on average, we check our phones for information roughly 150 times per day. And each time that we do that, we are likely to get lost in the phone with other applications, often spending more time on a task than is necessary or even completely forgetting what we were looking for on the phone in the first place.
The first devices boasting Android Wear were the Samsung Gear Live and LG G Watch, both of which were released at the time of Google I/O in June. Watches were the first target for Wear, and rightly so: A watch is something most people understand and use daily. These so-called “smart” watches work is are usually paired with an Android phone device, and Google has made sure that users immediately see the Wear platform at work by making it work seamlessly with latest Android phones.
In fact, to get started with Android Wear, all you need is the following:
- An Android 4.3 device
- The Android Wear Application from Google Play Marketplace.
- The ability to pair up your Android phone device with the Wear Device.
That’s it. And with these things in place, most of the notifications you get on your phone will be reflected on your Wear device. Not only will you see these notifications on the watch, but you will also be able to interact with them, dismiss them, and so on. What this shows is that without any (or with little) effort, Android applications work with paired devices—a model that Android phone users can relate to.
It’s important to keep in mind that the bridge between the phone and the Wear device is provided over Bluetooth. Wear devices currently available do not have the ability to access the Internet on their own, so the connection has to happen via a phone.
While Android Wear is flexible, right now watches are getting most of the Wear-related attention.
In early September, Motorola released its much-anticipated smartwatch, the Moto 360, based on Android Wear. The Moto 360 has earned praise for its beautiful design, and, at a price point of about $250, it has seen a good response from consumers. Other vendors, including ASUS, have announced plans to release their own smartwatches based on Android Wear.
Usage Patterns
There are two main ways users interact with an Android Wear device: Suggest and Demand.
Suggest, as the name indicates, comprises useful and timely information that is pushed to the Wear device, in the form of a notification. The user interface refers to this as a Card, examples of which are shown below.
The important thing to note here is that the Wear application is aware of context and thus pushes only information that is relevant within context. These kinds of notifications should be timely, short and easy to read, and requires minimal interaction with the user.
Use cases for Suggest include instant messages, flight schedule changes, stock updates and weather.
With the Demand usage pattern, users speak (via voice) to the wearable and it responds back with information. The devices have a microphone that lets users invoke a list of standard actions to perform by saying “OK, Google” or by tapping on the home screen. The user interface prompts users to speak which action they would like to perform. The list of standard actions includes “take a note,” “call someone” and “send a message.” Your own applications can register for the standard actions or your own customized cue text.
Design Philosophy
Now that we have examined the basic usage patterns in Android Wear, it is time to look at the user interface and some of its guiding design principles.
Most information is presented to the user in the form of a card, as shown below:
Notice the different parts of the card. With very little (or even no) modification, your current Android app notifications will come up in the format above. But since we are talking about minimal information that needs to be easy to read and contextually relevant, you should definitely spend some time thinking about when to raise the notifications and how much of text needs to be shown.
Notifications can be shown on single or multiple cards. If multiple cards are used, the user swipes left to right to move between the pages.
You can even provide more than one notification by stacking them together, as shown below:
There are four key things to keep in mind when designing Android Wear experiences, as per the Google Wear Design Creative Vision section. Android Wear applications should:
- Launch automatically: Users should not need to reach out to launch apps on a Wear device. A Wear device is not a phone. The Wear app should be aware of the context—time, location and activity—and should insert the relevant card accordingly.
- Be “glanceable”: Since users are wearing the devices on their wrists, it should be as easy to read the notification as it is to see the time on a traditional watch. Keeping that in mind, pay special attention to the title/text: Keep it to a minimum—easy to read at a glance and relevant.
- Effectively leverage Suggest and Demand: According to the Android Wear developer page, “Android Wear is like a great personal assistant … it only interrupts you when absolutely necessary, and it’s always on hand to provide a ready answer.” To offer this experience, developers should be thoughtful about when and how they use the Suggest and Demand models.
- Require zero to low interaction with the user: It’s important to develop applications with the typically small size of wearable devices in mind. Applications have to be easy for users to interact with, which means using voice or simple swipe/tap gestures.
The Wear Design team has down a great job in documenting how to effectively integrate the Design philosophy when creating wearable extensions of your existing Android applications. (Check out the Design section on Android Wear.)
Development Details
In this section, we are going to look at key concepts to get you started with Android Wear development.
You can use either Eclipse or Android Studio as your IDE of choice for Wear development. Google recommends Android Studio for development. Use the SDK Manager in Android to download API Level 20 (4.4 KitKat Wear):
Android Studio provides a convenient way to add Android Wear support to your existing applications or to create a new project: Android Studio uses a module model, where the Phone and Wear modules are part of a single project.
To create a new project in Android Studio, click on File -> New Project. On the second wizard screen, where you need to select the form factor, make sure to select the Android Wear module among any other form factor you are developing for (see below).
Once you have chosen all of your options, a project will be generated for you. You will notice that this Android project has two modules: mobile and wear. Mobile is the application that will run on a phone device, and Wear is the application that will run an Android Wear device.
Wear applications cannot be packaged separately and put on Google Play store. You will need to package your mobile and Wear app into the application APK. When the user installs the APK on his or her phone, the Wear app will be automatically transferred over to the paired Wear device.
The default project generated by Android Studio does not do anything special. During tests we had to write our own code, depending on what we wanted the “wearable” part of the application to do.
Notifications
Android Wear development can be looked at from two angles: Notifications and Android Wear Apps themselves (packaged via the APK file).
For users who have the official Android Wear application installed from Play Store on their phones, and who have paired the phones with their Wear devices, notifications will appear without any changes needed in an application.
With that said, sometimes modifications are necessary in order for apps to be truly useful on the Wear platform.
You can have notifications that are available only on a phone device, only on a wearable, or both. Additionally, as noted earlier, developers should be thinking about how to take advantage of the UI —background image, notification title, notification text, and so on.
To build handheld notifications that will also be sent to a wearable, Google recommends using the NotificationCompat.Builder class. A set of these classes is provided in the Android Support Library that you will need to add to your project.
If using Android Studio, you need to add the following compile time dependency to your build.gradle file in the mobile module:
compile «com.android.support:support-v4:20.0.+» To build a notification, you can try out the following code in your mobile application:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle(“New API”)
.setContentText(“XYZ API got added to Food Category”)
.setSmallIcon(R.drawable.ic_mynotification)
.setContentIntent(PhoneActivityPendingIntent); Next, you can trigger the notification based on your logic, as shown below:
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, notificationBuilder.build()); Now, when users receive the notification on his or her Wear device, they can launch the Pending Intent activity on their phones by touching the notification or even by swiping to the left, which will show an Open action.
As an extension, say you wanted the notification to appear only on a phone device, you could build the notification by specifying the .setLocalOnly(true).
In the example above, we have shown only one card, but you could look at a notification that contains multiple pages or even stacked notifications.
Wearable Applications
While Android Wear provides support for notifications from a phone, there are times when it is not sufficient. There can be several scenarios, including the following:
- Launch an activity on the wear device if some data is received on the phone.
- Send a message from the Wear device to the phone, which in turn will execute some activity or even do something in the background
- Create custom UI on the Wear device
- Write an application that is launched and run on the Wear device, and that is capable of accepting voice input to drive various actions.
All of the above and much more is possible, but only if you understand a few building blocks of the Wear APIs.
Connection and Data Exchange
In the use cases provided earlier, the common theme is that both the phone and the Wear device need a mechanism to establish a connection with each other, and then—once the connection is established—exchange messages between each other. This, in turn, can trigger the appropriate action on the respective devices.
This connection between a phone and Wwear device is provided by Google Play Services. This connection is provided by an instance of the GoogleAPIClient.
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build(); You can establish and close the connection in the appropriate Activity Lifecycle methods, as shown below:
@Override
protected void onStart() <
super.onStart();
mGoogleApiClient.connect();
>
@Override
protected void onStop() <
super.onStop();
mGoogleApiClient.disconnect();
> Once the connection is established, you can look at various example APIs to facilitate sending and syncing data between devices:
- Node API: This API is used to keep a track when the two devices are connected or disconnected via the NodeListener interface methods. It also provides a method for getting a list of all connected nodes.
- Message API: This API is used to send across short messages to either side. There needs to be a listener on the receiving side (MessageListener) that can get the message.
- Data API: This API is used to sync data between the two devices. The platform takes care of providing the sync mechanism on both sides. To receive a message, you need to implement the DataListener interface It is recommended that you create an instance of the WearableListenerService on both sides and listen for the events that you are interested in.
The Data Layer Interfaces are shown below; use the one(s) appropriate for the job.
static interface DataListener <
void onDataChanged(DataEventBuffer dataEvents);
>
static interface MessageListener <
void onMessageReceived(MessageEvent messageEvent);
>
static interface NodeListener <
void onPeerConnected(Node node);
void onPeerDisconnected(Node node);
> The rest of the functionality—that is, what action needs to be taken in the case of a particular message—is entirely up to the functionality of your application.
Example In Action
To put it all in context, let’s look at an example application, with phone and Wear components. To keep things simple, the phone application will have a single activity named MainActivity.java. Its layout will have a button, which, when clicked on, will send a message to the Wear application.
First, let’s look at the MainActivity.java in the Phone application (main methods are shown):
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener <
protected void onCreate(Bundle savedInstanceState) <
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
>
@Override
protected void onStart() <
super.onStart();
mGoogleApiClient.connect();
>
@Override
protected void onStop() <
mGoogleApiClient.disconnect();
super.onStop();
>
//Button click
public void onSendMessage(View view) <
//Get Connected Nodes
Collection nodes = getNodes();
//For each node — send the message across
for (String node : nodes) <
SendMessageResult result = Wearable.MessageApi.sendMessage(
mGoogleApiClient, node, «/startactivity» , null).await();
if (!result.getStatus().isSuccess()) <
//Log Message Success
>
>
>
@Override
public void onConnectionSuspended(int i) <
Log.e(TAG, . );
>
@Override
public void onConnectionFailed(ConnectionResult connectionResult) <
Log.e(TAG, . );
> On the receiving side—that is, Wear—we wrote a service that extends the WearableListenerService. Using this service, you can initialize the GoogleAPIClient and other callbacks like GoogleApiClient.ConnectionCallbacks.
Finally, we provided an implementation on onMessageReceived as shown below: @Override
public void onMessageReceived(MessageEvent messageEvent) <
if (messageEvent.getPath().equals(«/startactivity»)) <
Intent startIntent = new Intent(this, WearActivity.class);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startIntent);
>
Custom UI and Voice Actions
In addition to data APIs, Wear provides facilities for allowing developers to create a Custom UI using various components geared toward wearables.
There is an unofficial library that you can use today.
Voice Integration provides the standard ability to allow the user to provide voice input that can be interpreted as text. Following the Demand usage pattern, user can—via voice—invoke an application or action.
Conclusion
Android Wear is a great platform for building wearable applications for the first set of wearable devices based on the platform—smartwatches.
Google has been particular in stressing to developers the need to respect the user and follow its vision when it comes to wearable applications. By making existing applications Wear-ready via notifications, the barrier to writing applications for wearable devices is kept to a minimum. There is a growing list of applications designed for Wear on the Play store, including a huge rise in the number of watch faces available—a favorite app for users. Given that more vendors have announced plans for Android Wear devices and with the given global market share of Android OS, developers should invest their time into this platform.
Источник