这是我参与8月更文挑战的第28天,活动详情查看:8月更文挑战
Bubble API
介绍
气泡是通过 Notification API 创建的,因此您可以照常发送通知。如果希望让通知显示为气泡,则需要为其附加一些额外的数据。
气泡的展开视图是根据您选择的 Activity 创建的。此 Activity 需要经过配置才能正确显示为气泡。此 Activity 必须可以调整大小且是嵌入式的。只要 Activity 不满足其中任何一项要求,都会显示为通知。
如果APP需要显示多个相同类型的气泡(例如与不同联系人的多个聊天对话),此 Activity 必须能够启动多个实例。在搭载 Android 10 的设备上,除非将 documentLaunchMode 明确设置为 "always",否则通知不会显示为气泡。从 Android 11 开始,您无需明确设置此值,因为系统会自动将所有对话的 documentLaunchMode 设置为 "always"。
<activity
android:name=".BubbleActivity"
android:theme="@style/Theme.AppCompat.NoActionBar"
android:allowEmbedded="true"
android:resizeableActivity="true"
android:documentLaunchMode="always"
android:exported="true" />
发送气泡的流程
- 按照常规方式创建通知。
- 调用
BubbleMetadata.Builder(PendingIntent, Icon)或BubbleMetadata.Builder(String)以创建 BubbleMetadata 对象。 - 使用
setBubbleMetadata()将元数据添加到通知中
private void sendBubble(){
// Create bubble intent
Intent target = new Intent(MainActivity.this, BubbleActivity.class);
PendingIntent bubbleIntent =
PendingIntent.getActivity(MainActivity.this, 0, target, 0 /* flags */);
// Create bubble metadata
@SuppressLint({"NewApi", "LocalSuppress"}) Notification.BubbleMetadata bubbleData =
new Notification.BubbleMetadata.Builder(bubbleIntent,
Icon.createWithResource(this, R.drawable.icon))
.setDesiredHeight(600)
.build();
// Create notification
Person chatPartner = new Person.Builder()
.setName("Chat partner")
.setImportant(true)
.build();
Notification.Builder builder =
new Notification.Builder(this, CHANNEL_ID)
.setContentIntent(contentIntent)
.setSmallIcon(smallIcon)
.setBubbleMetadata(bubbleData)
.addPerson(chatPartner);
}
注意:首次发送显示气泡的通知时,必须使用具有
IMPORTANCE_MIN或更高级别的通知渠道。
如果应用在发送气泡时位于前台,则系统会忽略重要程度,并始终会显示相应气泡(除非用户已屏蔽来自您应用中的气泡或通知)。
创建展开的气泡
可以将气泡配置为自动以展开状态显示。建议仅在用户执行会导致显示气泡的操作(例如点按按钮以开始新的聊天)时才使用此功能。在这种情况下,还有必要禁止显示在创建气泡时发送的初始通知。
可以使用以下方法设置启用这些行为的标志:setAutoExpandBubble() 和setSuppressNotification()。
Notification.BubbleMetadata bubbleData =
new Notification.BubbleMetadata.Builder()
.setDesiredHeight(600)
.setIntent(bubbleIntent)
.setAutoExpandBubble(true)
.setSuppressNotification(true)
.build();
气泡内容生命周期
如果展开气泡,内容 Activity 会完成常规进程生命周期,这会使应用成为前台进程(如果应用尚未在前台运行)。
如果收起或关闭气泡,系统会销毁此 Activity。这可能导致系统缓存此进程,然后将其终止,具体取决于应用是否有任何其他前台组件正在运行。