》Adding Voice Capabilities
Wear provides two types of voice actions:
-
System-provided
- These voice actions are task-based and are built into the Wear platform. You filter for them in the activity that you want to start when the voice action is spoken. Examples include "Take a note" or "Set an alarm". App-provided
- These voice actions are app-based, and you declare them just like a launcher icon. Users say "Start " to use these voice actions and an activity that you specify starts.
For example, for the "Take a note" command, declare this intent filter to start an activity namedMyNoteActivity
:
<activity android:name="MyNoteActivity"> <intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="com.google.android.voicesearch.SELF_NOTE" /> </intent-filter> </activity>In your app, you call
startActivityForResult()
using the
ACTION_RECOGNIZE_SPEECH
action. This starts the speech recognition activity, and you can then handle the result in
onActivityResult()
.
private static final int SPEECH_REQUEST_CODE = 0; // Create an intent that can start the Speech Recognizer activity private void displaySpeechRecognizer() { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); // Start the activity, the intent will be populated with the speech text startActivityForResult(intent, SPEECH_REQUEST_CODE); } // This callback is invoked when the Speech Recognizer returns. // This is where you process the intent and extract the speech text from the intent. @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == SPEECH_REQUEST_CODE && resultCode == RESULT_OK) { List<String> results = data.getStringArrayListExtra( RecognizerIntent.EXTRA_RESULTS); String spokenText = results.get(0); // Do something with spokenText } super.onActivityResult(requestCode, resultCode, data); }