標籤:android wear android 穿戴式裝置 分組
原文地址:http://developer.android.com/wear/notifications/stacks.html
前言
當在手持功能上建立通知的時候,你應該經常將一些類似的通知歸併到一個單一的摘要通知中。比如,如果你的應用接收到資訊後會建立通知,你不應該在手持功能上建立多條通知。當接收到多條資訊的時候,你應該使用一條單一的通知並顯示類似“2 new messages”這樣的摘要資訊。
但是,一個摘要通知在Android Wear裝置上就顯得沒那麼有用,因為使用者不能夠在穿戴裝置上詳細閱讀每條資訊(他們必須在手持功能上開啟你的應用程式來查看更多的資訊)。因此,在穿戴裝置上,你應該將所有通知歸檔到一個棧中。包含多個通知的棧將作為一張卡片顯示,使用者可以展開來查看每一條通知的詳細資料。新的setGroup()方法讓這一切成為可能,並且還能夠同時在手持功能上只保持提供一條摘要通知。
更多關於設計通知棧的內容,請參考Design Principles of Android Wear。
Add Each Notification to a Group(將每一條資訊分組)
建立一個棧,你需要為每條通知調用setGroup()方法,並指定分組的key。然後調用notfiy()方法將它發送到穿戴裝置上。
final static String GROUP_KEY_EMAILS = "group_key_emails";// Build the notification and pass this builder to WearableNotifications.BuilderNotificationCompat.Builder builder = new NotificationCompat.Builder(mContext) .setContentTitle("New mail from " + sender1) .setContentText(subject1) .setSmallIcon(R.drawable.new_mail);Notification notif1 = new WearableNotifications.Builder(builder) .setGroup(GROUP_KEY_EMAILS) .build();// Issue the notificationNotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);notificationManager.notify(notificationId1, notif);
之後,當你建立其它通知的時候,只要你指定相同的分組key。那麼你調用notify()方法之後,這條通知就會跟之前的通知一樣出現在相同的通知棧裡面,並替代成為一張新的卡片:
builder = new NotificationCompat.Builder(mContext) .setContentTitle("New mail from " + sender2) .setContentText(subject2) .setSmallIcon(R.drawable.new_mail);// Use the same group as the previous notificationNotification notif2 = new WearableNotifications.Builder(builder) .setGroup(GROUP_KEY_EMAILS) .build();notificationManager.notify(notificationId2, notif);
預設情況,通知的顯示順序由你的添加順序決定,最近添加的通知將會出現在最頂部。你也可以為通知在棧中指定一個序號,只要你將序號作為setGroup()方法的第二個參數傳遞進去。
Add a Summary Notification(添加一條摘要通知)
在手持功能上保持提供一條摘要通知是相當重要的。因此,除了將每一條通知添加到相同的棧中之外,還要添加一條摘要通知到棧中,只不過要把摘要通知的序號設定為GROUP_ORDER_SUMMARY。
這條摘要通知不會出現在穿戴裝置上的通知棧中,但是會作為一條通知出現在手持功能上。
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_large_icon);builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_small_icon) .setLargeIcon(largeIcon);// Use the same group key and pass this builder to InboxStyle notificationWearableNotifications.Builder wearableBuilder = new WearableNotifications .Builder(builder) .setGroup(GROUP_KEY_EMAILS, WearableNotifications.GROUP_ORDER_SUMMARY);// Build the final notification to show on the handsetNotification summaryNotification = new NotificationCompat.InboxStyle( wearableBuilder.getCompatBuilder()) .addLine("Alex Faaborg Check this out") .addLine("Jeff Chang Launch Party") .setBigContentTitle("2 new messages") .setSummaryText("[email protected]") .build();notificationManager.notify(notificationId3, summaryNotification);
這條通知使用了NotificationCompat.InboxStyle,它提供了一種為郵件或者資訊類應用程式建立通知的簡單方法。你可以採用這種風格,而其它的通知使用NotificationCompat來定義,當然你也可以完全不是用這種風格來定義摘要通知。
提示:定義類似中的文字風格,可以參考Styling with HTML markup和Styling with Spannables.