创建通知
private void createNotification(String title, String description) {
if (getContext() == null || getActivity() == null) {
return;
}
NotificationManager notificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
// 设置通知点击事件
Intent notificationIntent = new Intent(getContext(), MainActivity.class);
notificationIntent.putExtra(NotificationConstants.NOTIFICATION_KEY, NotificationConstants.NOTIFICATION_VALUE);
PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Notification.Builder notificationBuilder;
// 创建通知渠道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(NotificationConstants.NOTIFICATION_CHANNEL_ID, NotificationConstants.NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(NotificationConstants.NOTIFICATION_CHANNEL_DESC);
notificationManager.createNotificationChannel(channel);
// 构建通知
notificationBuilder = (new Notification.Builder(getContext(), NotificationConstants.NOTIFICATION_CHANNEL_ID))
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.app_icon))
.setSmallIcon(R.drawable.app_icon)
.setContentTitle(title)
.setContentText(description)
.setContentIntent(pendingIntent);
} else {
// 构建通知
notificationBuilder = new Notification.Builder(getContext())
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.app_icon))
.setSmallIcon(R.drawable.app_icon)
.setContentTitle(title)
.setContentText(description)
.setContentIntent(pendingIntent)
.setPriority(Notification.PRIORITY_DEFAULT);
}
// 发送通知
Notification notification = notificationBuilder.build();
notificationManager.notify(NotificationConstants.NOTIFICATION_ID, notification);
}
收到通知点击跳转后
(1)在跳转的activity 重写onNewIntent
(2)注意根据需求场景设置activity的launchMode
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent != null && intent.getExtras() != null) {
String source = intent.getStringExtra(NotificationConstants.NOTIFICATION_KEY);
if (source != null && source.equals(NotificationConstants.NOTIFICATION_VALUE)) {
// 从通知点击进入的逻辑
LogUtil.i("shawn", "从通知点击进入");
}
}
}
图标空白的问题
-
图标资源问题:确保你使用的通知图标资源是有效的、存在的,并且已经正确放置在相应的drawable目录下。通常,在res/drawable目录中放置通知图标资源。
-
图标尺寸问题:Android对通知图标有一定的尺寸要求。通常,通知图标的尺寸应为24x24dp,对于高分辨率屏幕也可以使用48x48dp。如果你的图标尺寸不符合要求,可能会导致图标显示异常。
-
图标颜色问题:通知图标应该是单色的,使用白色或者透明色的图标,以确保在各种背景下都能显示正常。
-
图标透明度问题:如果图标资源中设置了透明度或alpha通道,确保透明度没有被设置为完全透明(alpha=0),否则图标将不可见
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
builder.setSmallIcon(R.mipmap.icon);
} else {
// 背景透明的图片,配上底色
builder.setSmallIcon(R.mipmap.icon)
.setColor(Color.parseColor("#0972EE"));
}