环境
Gradle Plugin 7.0.3 Gradle 7.0.2 JDK 13.0.1 Android Studio Arctic Fox
使用
可以设置点击事件然后实现sendNotification逻辑,点击通知栏后跳转到新的Activity 设置通知的步骤如下 0.获取NOTIFICATION_SERVICE服务 1.设置NotificationChannel 2.为NotificationManager创建渠道 3.设置Notification.Builder 4.Build & notify
private void sendNotification(){
String CHANNEL_ID = "channel_id";
String CHANNEL_NAME = "channel_name";
int NOTIFY_ID = 1;
Bitmap bigBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.test);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID,CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(notificationChannel);
Notification.Builder builder = new Notification.Builder(this,CHANNEL_ID);
Intent intent = new Intent(UIActivity.this, NotificationActivity.class);
PendingIntent pit = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentTitle("通知的标题")
.setContentText("通知的内容")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(bigBitmap)
.setContentIntent(pit);
Notification notification = builder.build();
notificationManager.notify(NOTIFY_ID, notification);
}
}
其中通过NOTIFY_ID来取消Notification
notificationManager.cancel(NOTIFY_ID);
除了上述代码中的属性,Notification.Builder还有许多可设置的属性
.setSubText("子内容")
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
|