今天看Android书上关于Notification的代码
<span style="white-space:pre"> </span>Intent i = new Intent(this,NotificationActivity.class);
i.putExtra("notificationID",notificationID);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,0);
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(
R.mipmap.ic_launcher,
"Reminder:Meeting starts in 5 minutes",
System.currentTimeMillis());
CharSequence from = "System Alarm";
CharSequence message = "Meeting with customer at 3pm...";
notif.setLatestEventInfo(this,from,message,pendingIntent);
<span style="white-space:pre"> </span>notif.vibrate = new long[]{100,250,100,500};
nm.notify(notificationID,notif);
功能成功实现了。但是发现Notification的构造函数和setLatestEventInfo函数已经不推荐使用了,官方建议使用Notification.Builder来代替。
参照文档,我这样写了。
Notification notif = new Notification.Builder(this)
.setContentIntent(pendingIntent)
.setTicker("Reminder:Meeting starts in 5 minutes")
.setContentTitle("System Alarm")
.setContentText("Meeting with customer at 3pm...")
.build();
发现并没有在通知栏中显示通知。
后来在 这里 找到了这样的话:
A Notification object must contain the following:
A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()
Notification notif = new Notification.Builder(this)
.setContentIntent(pendingIntent)
.setTicker("Reminder:Meeting starts in 5 minutes")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("System Alarm")
.setContentText("Meeting with customer at 3pm...")
.build();
难道必须三者都指定才能显示通知吗?我进行了尝试,如果不调用
setContentTitle() 或 setContentText()
是不会有问题的。
但是,不调用
setTicker("Reminder:Meeting starts in 5 minutes")
会造成通知栏不显示非展开模式的通知,只显示展开模式下的通知。
如果不调用
<strong>setSmallIcon(R.mipmap.ic_launcher)</strong>
一定不显示通知,包括展开模式下的。
上图: