今天在API Level 23上使用Notification的时候遇到了点问题,于是就去查了一下. 发现在不同的版本下,使用的方式存在着一些差异.
1. API Level < 11
在API Level < 11的版本下, 通知的实现方法是使用LatestEventInfo()方法. 在很多网上的资料和书籍上都有例子.
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, "tickerText", System.currentTimeMillis());
notification.setLatestEventInfo(this, "Title", "Text", null);
manager.notify(1, notification);
2. 11 < API Level < 16
此时就要在Notification.Builder里设置通知的参数了.
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(NotificationActivity.this);
builder.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Title")
.setTicker("Ticker")
.setContentText("Text")
.setWhen(System.currentTimeMillis())
.setContentIntent(null);
Notification notification = builder.getNotification();
3. 16 < API Level
此时,推荐使用build()方法来设置通知的参数.不过,Notification.Builder也能用.
Notification notification = new Notification.Builder(NotificationActivity.this)
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.zaza)
.setContentTitle("Title_one")
.setContentText("Text_one")
.build();
获取版本的方法 : Build.VERSION.SDK_INT.
if(Build.VERSION.SDK_INT > 16){
......
}