語音操作對于穿戴式應用的體驗非常重要.可以讓使用者不用手就可以快速的操作.wear提供了兩種類型的語音操作:
1.系統提供的
這類語音操作依賴系統平臺.當語音操作的時候你可以通過過濾來啟動你想啟動的頁面.比如:記筆記或者設置鬧鐘.
2.應用提供的
這類語音操作依賴于你的應用,你可以像聲明一個啟動圖標一樣聲明它們.用戶說`Start`去使用語音操作啟動你想啟動的activity.
聲明系統提供的語音操作
android wear 平臺系統本身提供了一些語音操作比如Take a note
,Set an alarm
.這樣用戶說出他們希望做的事情系統會進行辨別相應的activity去啟動.
當用戶說語音操作時,你的應用可以過濾你想啟動頁面的意圖.如果你想啟動一個服務在后臺做一些事情,應該先顯示一個頁面然后在這個頁面中啟動服務.當你想退出這個頁面的時候記得調用finish()方法.
舉個列子,將Take a note
命令聲明在MyNoteActivity
頁面中.
<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>
下面是Wear平臺支持的一些系統語音操作列表.
名字 | 示例短語 | 目標意圖 |
---|---|---|
打車 | "OK Google, get me a taxi""OK Google, call me a car" | Action com.google.android.gms.actions.RESERVE_TAXI_RESERVATION |
... | ... | ... |
聲明應用提供的語音操作
如果系統提供的語音操作沒有適合你的,你可以聲明自己的語音操作.
注冊一個啟動操作和在手機上注冊一個啟動圖標一樣.此時你的應用會啟動語音操作而不是啟動應用.
要指定Start
之后說出的文本需要為你想啟動的activity指定一個label
屬性.例如,意圖過濾器識別Start MyRunningApp
語音操作并啟動StartRunActivity
.
<application>
<activity android:name="StartRunActivity" android:label="MyRunningApp">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
獲取自由形式的語音輸入
除了使用語音操作去啟動activity,你也可以調用系統內置的語音識別器獲取用戶的語音輸入.這獲取用戶的輸入是非常有用的,比如搜索或者發信息.
在你的應用中可以調用[startActivityForResult()](https://developer.android.com/reference/android/app/Activity.html#startActivityForResult(android.content.Intent, int))設置ACTION_RECOGNIZE_SPEECH.啟動識別語音的頁面,你就可以在[onActivityResult()](https://developer.android.com/reference/android/app/Activity.html#onActivityResult(int, int, android.content.Intent))這個方法里處理結果.
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);
}