1、基本的
Android5.X通知栏做了改进,而且长按的时候会显示消息来源。
-
获取管理者
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
-
创建
Notification.Builder builder = new Notification.Builder(MainActivity.this); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.baidu.com")); PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,intent,0); //点击跳转 builder.setSmallIcon(R.mipmap.ic_launcher); //小图标,在大图标右下角 builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher)); //大图标,没有设置时小图标就是大图标 builder.setContentIntent(pendingIntent); builder.setAutoCancel(true); //点击的时候消失 builder.setContentTitle("Basic"); builder.setContentText("I am a basic notification"); builder.setSubText("I'm a test"); //别的其他信息 manager.notify(1,builder.build()); //参数一为ID,用来区分不同APP的Notification
2、折叠式Notification
-
折叠式Notification也是一种自定义视图的Notification,常常用于显示长文本,它拥有两个视图状态,一个的普通状态下的视图状态,另一个是展开状态下的视图状态。
Notification.Builder builder = new Notification.Builder(MainActivity.this); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.baidu.com")); PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,intent,0); //点击跳转 builder.setSmallIcon(R.mipmap.ic_launcher); //没设置发不出通知 builder.setContentIntent(pendingIntent); builder.setAutoCancel(true); //点击的时候消失 Notification notification = builder.build(); RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.notification1); notification.contentView = remoteViews; notification.bigContentView = remoteViews; manager.notify(1,notification);
3、悬挂式Notification
-
悬挂式Notification是在Android5.0中新增加的方式,会悬挂在屏幕上方一段时间:
Notification.Builder builder = new Notification.Builder(MainActivity.this) .setSmallIcon(R.mipmap.ic_launcher) .setPriority(Notification.PRIORITY_DEFAULT) .setCategory(Notification.CATEGORY_MESSAGE) .setContentTitle("Head") .setContentText("I am a head notify"); Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setClass(MainActivity.this,MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT); builder.setFullScreenIntent(pendingIntent,true); //重点就是这句 manager.notify(1,builder.build());
4、显示等级的Notification
-
Android5.X新加入一种新的模式——Notification的显示等级,分为三个等级:
VISIBILITY_PRIVATE:表明只有当没有锁屏的时候会显示。
ViSIBILITY_PUBLIC:表明在任何情况下都会显示。
ViSIBILITY_SECRET:表明在pin、password等安全锁和没有锁屏是情况下才能够显示。
设置等级非常简单:builder.setVisibility(Notification.VISIBILITY_PRIVATE);
网友评论