通知栏
在Android 8.0 之后,必须设置通知通道(notification channel)才能正常显示通知。
Intent intent = new Intent(this,NotificationActivity.class);
@SuppressLint("UnspecifiedImmutableFlag") PendingIntent pi = PendingIntent.getActivity(this,0,intent ,0);
String CHANNEL_ID= "channel_1";
String CHANNEL_NAME = "my_channel";
NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableVibration(true);//设置振动
manager.createNotificationChannel(notificationChannel);
Notification notification = new Notification.Builder(this)
.setChannelId(CHANNEL_ID)
.setContentTitle("This is content title")
.setContentText("This is content text")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
.setContentIntent(pi)
.setAutoCancel(true)
.setStyle(new Notification.BigTextStyle()
.bigText("adsfasdfadsfasdfadsfadfadsfadsfasdfadsfsdfdsfadsfadf"))
.setStyle(new Notification.BigPictureStyle()
.bigPicture(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher)))
.build();
manager.notify(1,notification);
} else {
Notification notification = new Notification.Builder(this)
.setContentTitle("This is content title")
.setContentText("This is content text")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher_round))
.setContentIntent(pi)
.build();
manager.notify(1,notification);
}
通过 PendingIntent 可以设置点击通知后的动作
setAutoCancel(true) 设置点击后消失
setStyle() 可以设置大视图下的bigText以及bigPicture
ContentTitle、ContentText、SmallIcon是必须设置的。
这里操作的时候有一个错误:通知栏报错
注意,小米手机默认会将该应用通知收进不重要通知中(即使设置了重要程度),需要手动设置。