Last week I wrote a post on how easy it is to add text-to-speech capability to your Android applications.  It’s easy because Google’s speech API
does all the heavy lifting for us. But the API doesn’t stop at speaking text
aloud — it also allows you to speak to the device and then translates those
voice commands into text an application can use.

This tutorial demonstrates how to add voice recognition to
your next Android app. Feel free to follow along or download the entire project
and import it directly into Eclipse.

Create a new Android project in Eclipse.  Target Android 2.2 or higher.

In the /res/layout directory, modify the
activity_main.xml file to include a text view and an image button.


In the /src folder, open The
on create override should look familiar; it simply wires up the button.
package com.authorwjf.talk2me;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

protected static final int REQUEST_OK = 1;

protected void onCreate(Bundle savedInstanceState) {


The on click handler is responsible for firing
off the voice intent.

public void onClick(View v) {
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(i, REQUEST_OK);
} catch (Exception e) {
Toast.makeText(this, "Error initializing speech to text engine.", Toast.LENGTH_LONG).show();

When the intent calls back, we display the
transcribed text.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_OK && resultCode==RESULT_OK) {
ArrayList thingsYouSaid = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

Load the resulting APK to your Android device via a USB
cable and try it out.

If your device isn’t running JellyBean, you will need Internet
connectivity for the voice input to work.
If your device is running JellyBean, you can go to Settings | Language
& Input | Voice Search and download the offline speech recognition pack.