Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Wear:在穿戴裝置中運用語音互動

編輯:關於 Android 程式設計

穿戴裝置通常沒有實體鍵盤,因此語音成為使用者與裝置互動的重要方式。Android Wear 提供了完整的語音輸入機制,讓使用者能透過說話快速回覆通知等操作。

在通知中接收語音輸入

當手機中建立了一個帶有某種行為的通知(例如回覆郵件)時,若在穿戴裝置上,就沒有鍵盤可供輸入。此時可透過 RemoteInput 讓使用者以語音或其他支援的方式輸入。當使用者說出回覆內容後,系統會將文字答覆綁定到你指定的通知行為 Intent 中,並傳回手機的 App。

定義語音輸入

要建立一個能接受語音輸入的行為,需實例化 RemoteInput.Builder 並加入通知的 action。它的構造方法接收一個字串,作為系統語音輸入的 key,以便之後將語音輸入與 App 關聯:

// 傳遞於 action intent 中的字串 key
private static final String EXTRA_VOICE_REPLY = "extra_voice_reply";
String replyLabel = getResources().getString(R.string.reply_label);
RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY)
    .setLabel(replyLabel)
    .build();

提供預定義的文字回覆

除了語音輸入,你也能提供最多五個讓使用者快速選擇的文字回覆,透過 setChoices() 傳入字串陣列。先在資源檔中定義回覆選項:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="reply_choices">
        <item>Yes</item>
        <item>No</item>
        <item>Maybe</item>
    </string-array>
</resources>

接著取得陣列並加入 RemoteInput:

String[] replyChoices = getResources().getStringArray(R.array.reply_choices);
RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY)
    .setLabel(replyLabel)
    .setChoices(replyChoices)
    .build();

將語音輸入作為通知行為

使用 addRemoteInput() 將 RemoteInput 綁定到 action 上,再透過 WearableExtender 加入通知:

// 建立回覆行為的 intent
Intent replyIntent = new Intent(this, ReplyActivity.class);
PendingIntent replyPendingIntent = PendingIntent.getActivity(
    this, 0, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

// 建立回覆 action 並加入 remote input
NotificationCompat.Action action = new NotificationCompat.Action.Builder(
    R.drawable.ic_reply_icon,
    getString(R.string.label, replyPendingIntent))
    .addRemoteInput(remoteInput)
    .build();

// 建立通知並透過 WearableExtender 加入 action
Notification notification = new NotificationCompat.Builder(mContext)
    .setSmallIcon(R.drawable.ic_message)
    .setContentTitle(getString(R.string.title))
    .setContentText(getString(R.string.content))
    .extend(new WearableExtender().addAction(action))
    .build();

// 發送通知
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mContext);
notificationManager.notify(notificationId, notification);

通知彈出後,使用者向左滑動螢幕,即可看到 reply 行為按鈕。

接收語音輸入作為字串

要接收使用者說出的語音,可調用 getResultsFromIntent(),它會返回一個包含文字回覆的 Bundle,再從中查詢對應內容。注意此處不能使用 Intent.getExtras():

private CharSequence getMessageText(Intent intent) {
    Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
    if (remoteInput != null) {
        return remoteInput.getCharSequence(EXTRA_VOICE_REPLY);
    }
    return null;
}

透過這套機制,穿戴裝置上的使用者就能以最自然的方式——說話——完成各類互動操作。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved