Channels ▼
RSS

Embedded Systems

The Wearable Computing Revolution Begins: Building Android Wear Apps


Android Wear provides two different ways of launching a wearable app. If you touch the device's face, a list of actions will appear. You just need to scroll down to find the Start… option, tap it ,and select your app from the list of installed apps. In this case, if you build the project and run the wear module, you will see the app listed as SpeechWear.

Android Wear supports voice activation to launch wearable apps. If you say "OK Google" on an Android Wear device that is awake, Android will display a Speak now prompt, a white screen with a red g (see Figure 3).

Android Wear
Figure 3: Android Wear displaying a Speak now prompt.

You just need to say "Start SpeechWear" and your app will start after Android recognizes your Start voice command. The values in the AndroidManifest.xml file specify a label attribute for the activity that the voice command will start. The intent filter recognizes the value specified in manifest/application/activity/android:label after "Start," and launches .MyActivity. The following lines show the section within the manifest file that defines the application values and its intent filter. Notice that the value for @string/app_name is SpeechWear in the strings.xml file.

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.DeviceDefault" >
    <activity
        android:name=".MyActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Thus, your app supports voice activation out of the box. Just make sure that the app name that is associated with the intent filter is easy to remember for the user.

Working with the Speech Recognizer

After the user takes advantage of voice activation to launch the wearable app, you can use the speech recognizer to easily obtain input from the user. You can use the android.Speech.RecognizerIntent class that was introduced in API Level 3. The wearable app will use the connectivity in the paired handheld device and stream audio to Google servers to perform speech recognition.

The following lines show a new version of MyActivity.java for the wear module. The code starts an activity that prompts the user for speech with the Speak now prompt (see Figure 2) and then displays the recognized speech in a TextView. Of course, the UI is extremely simple and the example is meant to focus solely on the ability to use a well-known Android API in a wearable app with Android managing the communication with the handheld under the hood.

package com.example.gaston.speechwear;

import android.app.Activity;
import android.os.Bundle;
import android.support.wearable.view.WatchViewStub;
import android.widget.TextView;

import android.content.Intent;
import android.speech.RecognizerIntent;
import java.util.List;

public class MyActivity extends Activity {

    private static final int SPEECH_RECOGNIZER_REQUEST_CODE = 0;

    private TextView mTextView;

    private void startSpeechRecognition() {
        // Create an intent to start the Speech Recognizer
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        // Start the activity
        startActivityForResult(intent, SPEECH_RECOGNIZER_REQUEST_CODE);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
        stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
            @Override
            public void onLayoutInflated(WatchViewStub stub) {
                mTextView = (TextView) stub.findViewById(R.id.text);
                startSpeechRecognition();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == SPEECH_RECOGNIZER_REQUEST_CODE) {
            // When the speech recognizer finishes its work, Android invokes this callback with requestCode equal to SPEECH_RECOGNIZER_REQUEST_CODE
            if (resultCode == RESULT_OK) {
                List<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                String recognizedText = results.get(0);
                // Display the recognized text
                mTextView.setText(recognizedText);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

The call to startSpeechRecognition creates an Intent to start the speech recognizer, and configures it to use the free form recognizer. The method calls startActivityForResult to start the activity and prompts the user for speech with SPEECH_RECOGNIZER_REQUEST_CODE as the request code.

When the speech recognition finishes, the app calls the onActivityResult callback with requestCode equal to SPEECH_RECOGNIZER_REQUEST_CODE. If the speech recognizer had successful speech recognition, the code displays the recognized text in the TextView.

With just a few lines of code, you can allow the user to speak to the Android Wear device. For example, imagine a simple application that converts units. You know how to measure distances in miles, but you travel to Italy and all the distances are expressed in kilometers. You are running or riding a bike and you don't want to use your smartphone and enter numbers with the keyboard. You see a distance in kilometers and you want to convert from kilometers to miles. You can talk to the Android Wear device to launch the app and convert the distance units. The sequence will be possible by adding just a few lines of code to the previous sample:

"OK Google Start Converter Twenty Kilometers to Miles"

"OK Google Start Converter" launches the app. Then, the app has to convert from text to numbers and parse the origin and destination units. Finally, the app displays the result. You can see the result and you don't have to stop moving.

Conclusion

As I mentioned earlier, it is necessary to shift your orientation before you start building Android wear apps. I've provided detailed instructions to prepare your development environment to start building Android Wear apps. I've provided only a simple example focused on speech recognition, which will enable you to employ your existing experience targeting Android smartphones and tablets. However, you will need to learn new APIs that allow you to make the wearable app interact with the handheld device if you want to build more-complex apps.


Gastón Hillar is a senior contributing editor at Dr. Dobb's.

Related Article

Hacking for Fun: Programming a Wearable Android Device


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.