Android Notification通知栏、点击事件、悬浮通知的简单实现

Notification的三要素

1.小图标 .setSmallIcon()
2.标题 .setContentTitle()
3.内容 .setContentText()
这是一个通知栏的 三要素 有了三要素你的通知栏才能显示出来

一些常用的方法
方法 效果
.setSmallIcon() 小图标
.setContentTitle() 标题
.setContentText() 内容
.setDefaults(Notification.DEFAULT_ALL); 提醒方式(ALL代表 声音 振动 提示灯兼备)
.setLargeIcon() 大图标
.setContentIntent() 点击跳转
.setWhen() 通知时间(何时通知)
.setAutoCancel(boolean) 点击后是否关闭通知
.setPriority(Notification.PRIORITY_MAX) 通知的优先级(MAX表示最高级)
API15以及以下的使用需要注意

1 .java代码中最后那条 .build()方法需要换成.getNotification()
如下: notificationManager.notify(0, builder.getNotification());
2. .setPriority() 方法不可用

接下来是完整的实现

java文件中

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(context);
builder.setContentTitle("危险警报!!!")
                        .setContentText("您的手机已经被病毒入侵,点击紧急杀毒")
                        .setSmallIcon(R.mipmap.jiaojing)
  notificationManager.notify(0, builder.build()); //API15以及以下需要把.build()方法需要换成.getNotification()          
Notification的点击事件

java代码如下
只需要实例化一个PendingIntent 利用 .setContentIntent()方法实现

 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.baidu.com/"));
 PendingIntent  pi = PendingIntent.getActivity(context, 0, intent, 0);
 NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
 Notification.Builder builder = new Notification.Builder(TongZhiActivity.this);
                builder.setContentTitle("标题")
                        .setContentText("内容(点击跳转至百度)")
                        .setSmallIcon(R.mipmap.jiaojing)
                        .setContentIntent(pi)    
                        .setAutoCancel(true)    //点击后关闭通知
                        .setWhen(System.currentTimeMillis()) ;
                notificationManager.notify(1, builder.build());
Notification悬浮通知
 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.baidu.com/"));
 PendingIntent  pi = PendingIntent.getActivity(context, 0, intent, 0);
 NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
 Notification.Builder builder = new Notification.Builder(TongZhiActivity.this);
                builder.setContentTitle("悬浮")
                        .setContentText("悬浮通知")
                        .setSmallIcon(R.mipmap.jiaojing)
                        .setContentIntent(pi)
                        .setAutoCancel(true)    //点击后关闭通知
                        .setWhen(System.currentTimeMillis())
                        .setDefaults(Notification.DEFAULT_ALL)
                        .setPriority(Notification.PRIORITY_MAX)
                        .setFullScreenIntent(pi, true);
                notificationManager.notify(3, builder.build());
发布了6 篇原创文章 · 获赞 5 · 访问量 241

猜你喜欢

转载自blog.csdn.net/qq_44720366/article/details/103495205