編輯:關於 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;
}
透過這套機制,穿戴裝置上的使用者就能以最自然的方式——說話——完成各類互動操作。
Android 四大元件之 Service:用法、溝通、生命週期與系統服務
一、Service 基本用法 先建一個 MyService 繼承自 Service,覆寫 onCreate()、onStartCommand() 與 onDestroy(
Retrofit 仿微信多張圖片拍照上傳
此範例延續仿微信發說說的場景,重點是拍照、相冊多選與 Retrofit 多圖上傳。客戶端選擇圖片後取得本地路徑,使用 Retrofit 的 multipart 介面將檔案
模版方法模式在 Android 中的應用實踐
模版方法模式(Template Method)模版方法模式屬於類的行為型模式。它提供一個抽象類,把一部分邏輯以具體方法或構造子的形式實現,然後聲明一些抽象方法,迫使子類去
Android 自定義控件(三):實現圓環式的百分比顯示
最近一直在啃自定義控件。昨天群裡有人問圓盤樣式的百分比該怎麼畫,正好學有所用,於是就有了這篇記錄。 先看效果,一目了然: 這裡的顯示顏色、每一段佔據的角度,都可以在布局