您的位置:首页 > 移动开发 > Android开发

关于Notification的一些变化

2016-08-30 20:54 274 查看

关于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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android 通知栏