android wear那些事--添加语音功能

Adding Voice Capabilities

语音操作对于穿戴式应用的体验非常重要.可以让使用者不用手就可以快速的操作.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()设置ACTION_RECOGNIZE_SPEECH.启动识别语音的页面,你就可以在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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值