Android Notification 通知 简单使用

人不应该一直怀念过去,要活在当下,所以我现在讲的这个Notification 的使用是在API16及以上的环境的,不兼容低版本

步骤开始:

1.我们先创建一个Notification ,看下面代码可以看出是使用的建造者模式,顺便给它设置三个基本属性,注意,没这三个基本属性它是活不了的

Notification notification = new Notification.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)//设置小图标
                .setContentTitle("这是标题")
                .setContentText("这是内容")
                .build();

2.获取Notification管理器

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

3.然后用这个Notification管理器把Notification弹出去,那个0是id,用来标识这个Notification的。

notificationManager.notify(0, notification);

4.最后我们发现点击弹出来的Notification没反应,因为我们没让它干嘛,所以我决定让它跳转到一个Activity里。这时候我们不是给它一个Intent,而是一个PendingIntent,意思就是等待的Intent,随时候着的意思,PendingIntent对Intent进行了包装,相当于将Intent跟Context进行打包,也就是PendingIntent是自带Context的,这样的话,就算应用程序关闭了,也不影响PendingIntent的启动。

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,TestActivity.class), 0);

notification.contentIntent = pendingIntent;

或者在创建的时候这样设置

.setContentIntent(pendingIntent)

5.我们可以给它设置了flag,让它被点击后自动清除。

notification.flags = Notification.FLAG_AUTO_CANCEL;

或者在创建的时候这样设置

.setAutoCancel(true)
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
AndroidNotification类中提供了`BigContentView`属性,可以实现通知不折叠。默认情况下,当通知内容过长时,系统会将通知折叠显示,只显示一部分内容。但是使用`BigContentView`属性后,可以实现通知的完全展开,显示所有的内容。 要使用`BigContentView`,首先需要创建一个RemoteViews对象,用于自定义通知的布局。然后,将该布局设置给`NotificationCompat.Builder`对象的`setCustomBigContentView()`方法。这样,系统在展示通知时,就会使用自定义布局,实现通知的不折叠。 以下是一个简单的示例代码: ```java // 创建自定义的BigContentView布局 RemoteViews bigContentView = new RemoteViews(getPackageName(), R.layout.notification_big); // 设置自定义布局到NotificationCompat.Builder对象 NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_notification) .setContentTitle("通知标题") .setContentText("通知内容") .setCustomBigContentView(bigContentView); // 发送通知 NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(notificationId, builder.build()); ``` 在上面的示例中,`notification_big`是一个自定义的布局文件,表示大尺寸通知的内容。你可以在该布局中设计显示所有的通知内容,包括标题、文字、图标等。然后,将该布局设置给`NotificationCompat.Builder`对象,即可实现通知的不折叠显示。 需要注意的是,某些设备可能无法显示大尺寸通知,而是将其折叠显示。这是由于设备厂商对通知的样式和布局进行了定制。因此,在使用`BigContentView`时,需要考虑设备和系统的兼容性,并进行适当的测试。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值