Android8.0之后,为了解决app为了提高曝光量不断发送垃圾通知的情况,Google为安卓引入了通知渠道的概念,每一条通知都要属于一个对应的渠道,而不同渠道的通知控制权在用户手中。
简单通知演示
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建通知管理器用于给通知编号和发送通知
NotificationManager manager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//判断版本等级,大于8.0才能创建通知渠道
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
//创建通知渠道,三个参数分别是,全局唯一的渠道id,用户所见渠道名称,初始渠道重要性
NotificationChannel channel = new NotificationChannel("ChannelId", "The name seen by the user", 2);
manager.createNotificationChannel(channel);
}
findViewById(R.id.button).setOnClickListener(v->{
//通过NotificationCompat的Builder类创建通知对象,第二个参数用于指定通知渠道
Notification notification=new NotificationCompat.Builder(this,"ChannelId")
.setContentTitle("This is content title")
.setContentText("This is content text")
//小图标,这是所必需的唯一用户可见内容。
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
.build();
manager.notify(1,notification);
});
}
这样的通知点击是没有反应的,像是按钮一样为他设置点击事件,这里需要用到PendingIntent(待定意图)来实现
//为通知设置点击效果,用Intent表达出想要启动的活动然后作为参数传入PendingIntent中作为参数传入即可
.setContentIntent(PendingIntent.getActivities(this,0,
new Intent[]{new Intent(this, TextActivity.class)},0))
设置长文本和图片
通知有许多属性,就从常见的长文本开始示例
//长文本
.setStyle(new NotificationCompat.BigTextStyle().bigText
("a\na\naaa\naaan\naaaa\naaaaaaaaaaaa\n"))
图片需要用BitmapFactory的decodeResource方法解析成Bitmap对象
设置弹出消息
将通知渠道的重要性设置成HIGH(4)即可。