关于Notification的一些变化

关于Notification的一些变化

今天在学习RemoteViews相关的知识到,书上提到了Notification的应用,但是其代码较为陈旧,有的方法甚至已经被Remove了,网上搜索到的也不是太全,现记录下来以作备用。

Notfication notification = new Notification();
notification.icon = R.drawable.ic_launcher;  //此格式已经被弃用
notification.tickerText = "hello world";
notification.when = System.currentTimeMillis();
notification.flags = Notification.FlAG_AUTO_CANCEL;
Intent intent = new Intent(this, DemoActivity_1.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
Notification.setLatestEventInfo(this,"chapter_5","this is notification.",pendingIntent);//此方法已经被Remove
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1,notification);

上述代码是书中原文,但是由于其中setLatestEventInfo方法已经被弃用,故无法运行,后查询官方说明文档,发现Notification的用法已经改变,应该使用构造器模式进行构造。

Example:
Notification noti = new Notification.Builder(mContext)
.setContentTitle("New mail from " + sender.toString())
.setContentText(subject)
.setSmallIcon(R.drawable.new_mail)
.setLargeIcon(aBitmap)
.build();

上述为官方说明文档给出的例子

故源代码应修改为:

Intent intent = new Intent(MainActivity.this,Demo.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),0,
                        intent,PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(getApplicationContext())
     .setSmallIcon(R.mipmap.ic_launcher)
     .setContentTitle("chapter_5")     //对应setLatestEventInfo的参数
     .setContentText("this is notification")   //对应setLatestEventInfo的参数
     .setTicker("hello world")
     .setPriority(Notification.PRIORITY_DEFAULT)
     .setDefaults(Notification.DEFAULT_ALL)
     .setContentIntent(pendingIntent)   //对应setLatestEventInfo的参数
     .setWhen(System.currentTimeMillis())
     .setAutoCancel(true)
     .build();   //build()方法返回的是Notification类的对象
NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
manager.notify(1,notification);

以上,更详细的学习Notification以及RemoteViews相关的信息可以浏览下方网页
Android 通知栏Notification的整合全面学习
Android-doc

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值