android 通知栏
2020-05-13 本文已影响0人
飞不起的小鸟
发送通知栏
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
private void sendNotification() {
//1、NotificationManager
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
/** 2、Builder->Notification
* 必要属性有三项
* 小图标,通过 setSmallIcon() 方法设置
* 标题,通过 setContentTitle() 方法设置
* 内容,通过 setContentText() 方法设置*/
Notification.Builder builder = new Notification.Builder(this);
builder.setContentInfo("Content info")
.setContentText("Content text")//设置通知内容
.setContentTitle("Content title ")//设置通知标题
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
.setSmallIcon(R.drawable.icon_notify)//不能缺少的一个属性
.setWhen(System.currentTimeMillis());//设置通知时间,默认为系统发出通知的时间,通常不用设置
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("001","my_channel",NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true); //是否在桌面icon右上角展示小红点
channel.setLightColor(Color.GREEN); //小红点颜色
channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
manager.createNotificationChannel(channel);
builder.setChannelId("001");
}
Notification n = builder.build();
//3、manager.notify()
manager.notify(1001,n);
}
关闭通知栏
private void cancelNotification(){
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(1001);
}