今天在学习安卓Notification的时候,按照书上的代码写了一个简单的案例,但是由于没有书上的图片资源,所以注掉.setSmallIcon(R.drawable.abc)这一行代码
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(MainActivity.this,SecondeActivity.class);
PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);
Notification notification =new Notification.Builder(this)
//.setSmallIcon(R.drawable.abc)
.setAutoCancel(true)
.setTicker("有新消息")
.setWhen(System.currentTimeMillis())
.setContentTitle("新消息来啦").setContentText("gggggg ").setContentIntent(pi).
build();
nm.notify(0x222,notification);
结果通知栏部分没有通知出现。
后来一个一个尝试后发现必须要有setSmallIcon(),哪怕仅仅只有setSmallIcon()都可以显示通知。通过查看NotificationManager.notify()代码发现在方法里面有判断过otification.getSmallIcon() == null,如果getSmallIcon为Null 会抛异常。
public void notifyAsUser(String tag, int id, Notification notification, UserHandle user)
{
int[] idOut = new int[1];
INotificationManager service = getService();
String pkg = mContext.getPackageName();
// Fix the notification as best we can.
Notification.addFieldsFromContext(mContext, notification);
if (notification.sound != null) {
notification.sound = notification.sound.getCanonicalUri();
if (StrictMode.vmFileUriExposureEnabled()) {
notification.sound.checkFileUriExposed("Notification.sound");
}
}
fixLegacySmallIcon(notification, pkg);
if (mContext.getApplicationInfo().targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
//如果没有setSmallIcon ,此处会抛异常
if (notification.getSmallIcon() == null) {
throw new IllegalArgumentException("Invalid notification (no valid small icon): "
+ notification);
}
}
if (localLOGV) Log.v(TAG, pkg + ": notify(" + id + ", " + notification + ")");
final Notification copy = Builder.maybeCloneStrippedForDelivery(notification);
try {
service.enqueueNotificationWithTag(pkg, mContext.getOpPackageName(), tag, id,
copy, idOut, user.getIdentifier());
if (id != idOut[0]) {
Log.w(TAG, "notify: id corrupted: sent " + id + ", got back " + idOut[0]);
}
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}