android之PendingIntent使用
默认 PendingIntent布局
NotificationManager mNotificationManager = (NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);
Notification mNotification = new Notification(R.drawable.icon,"This is a notification.",System.currentTimeMillis());
//将使用默认的声音来提醒用户
mNotification.defaults = Notification.DEFAULT_SOUND;
Intent mIntent = new Intent(mContext,TestNotificationActivity.class);
//这里需要设置Intent.FLAG_ACTIVITY_NEW_TASK属性
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent mContentIntent =PendingIntent.getActivity(mContext,0, mIntent, 0);
// //这里必需要用setLatestEventInfo(上下文,标题,内容,PendingIntent)不然会报错.
mNotification.setLatestEventInfo(mContext, "10086", "您的当前话费不足,请充值.哈哈~", mContentIntent);
// //这里发送通知(消息ID,通知对象)
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
自定义PendingIntent布局
NotificationManager mNotificationManager = (NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);
Notification mNotification = new Notification(R.drawable.icon,"This is a notification.",System.currentTimeMillis());
//将使用默认的声音和振动来提醒用户
mNotification.defaults = Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE;
//自定义界面
RemoteViews rv = new RemoteViews(getPackageName(), R.layout.notification);
rv.setTextViewText(R.id.notification_tv_one, "one");
rv.setTextViewText(R.id.notification_tv_two, "two");
rv.setTextViewText(R.id.notification_tv_three, "three" + System.currentTimeMillis());
rv.setImageViewResource(R.id.notification_image_one,R.id.notification_image_one);
mNotification.contentView = rv;
//点击notification之后,该notification自动消失
mNotification.flags = Notification.FLAG_AUTO_CANCEL;
//点击notification之后,像Android QQ一样能出现在 “正在运行的”栏目
// mNotification.flags = Notification.FLAG_ONGOING_EVENT;
//该意图用来打开NotificationList这个新的Activity
Intent mIntent = new Intent(mContext,TestNotificationActivity.class);
//这里需要设置Intent.FLAG_ACTIVITY_NEW_TASK属性
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//包装该Intent,只有包装后的Intent才能被Notification所用,这是因为Notification需要指定一些额外的参数
PendingIntent mContentIntent =PendingIntent.getActivity(mContext,0, mIntent, 0);
//这里必需要用setLatestEventInfo(上下文,标题,内容,PendingIntent)不然会报错.
mNotification.contentIntent = mContentIntent;
//这里发送通知(消息ID,通知对象)
//NOTIFICATION_ID由自己指定,为每一个Notification对应的唯一标志
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
注意,如果使用了contentView,那么便不要使用Notification.setLatestEventInfo。如果setLatestEventInfo在赋给 Notification.contentView 的代码之后,那么contentView的效果将被覆盖,显示的便是 setLatestEventInfo 的效果;如果 setLatestEventInfo 在 Notification.contentView 的代码之前,那么显示的便是 Notification.contentView 的效果,也就是说不管你想要setLatestEventInfo 或 contentView 的自定义效果,请保证始终只有一句设置代码,因为在最后一句绑定的时候,之前的设置contentView或setLatestEventInfo的代码都是完全没有必要的
取消通知
//取消只要把通知ID传过来就OK了.
mNotificationManager.cancel(NOTIFICATION_ID);