在Android中,使用BadgeView库可以在通知栏中显示一个小图标。以下是如何在通知栏中使用BadgeView的步骤:
dependencies {
implementation 'com.github.jorgecastilloprz:BadgeView:1.0'
}
<application
...
android:roundIcon="@mipmap/ic_launcher_round"
...>
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
private void createNotificationWithBadge() {
String channelId = "your_channel_id";
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Notification Title")
.setContentText("Notification content")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
// 创建一个BadgeView实例
BadgeView badgeView = new BadgeView(this, R.id.your_notification_button);
badgeView.setNumber(5); // 设置徽章数字
badgeView.setGravity(Gravity.TOP | Gravity.END); // 设置徽章位置
badgeView.setViewVisibility(View.VISIBLE); // 设置徽章可见
// 将BadgeView添加到通知的意图中
Intent intent = new Intent(this, YourActivity.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
// 创建一个通知
Notification notification = builder.build();
// 发送通知
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(NOTIFICATION_ID, notification);
}
<Button
android:id="@+id/your_notification_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notification Button" />
createNotificationWithBadge()
方法,以创建带有徽章的通知。现在,当您发送带有徽章的通知时,通知栏中应该会显示一个小图标。