Android的通知事件,可以在状态栏上面显示,滚动显示通知突然内容以及图标,可以设置在状态栏展开的时候,显示通知项的标题和内容,以及点击它所打开的应用程序。。。
NotificationManager,通过getSystemService(Context.NOTIFICATION_SERVICE);来获取系统的通知管理器
新建一个通知事件,Notification notification = new Notification(R.drawable.icon, “状态栏上滚动显示的标题”, System.currentTimeMillis());
其中第一参数为notification在状态栏上显示的图标,第二个为添加时状态栏上显示的标题,最后为通知事件添加的时间。
通过notification.flags参数设置通知事件的标志,如是属于“正在进行的”还是“通知”等,具体得看reference了,,,
notification.flags |= Notification.FLAG_ONGOING_EVENT;
设置状态栏展开时,通知事件的标题和内容,以及点击所打开的程序。
Intent intent = new Intent(mContext, NotificationCancelAll.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
notification.setLatestEventInfo(mContext, "NotificationTitle",
"Notification Content!", pendingIntent);
如果有需要可以,自己定义在状态展开时所显示的view
RemoteViews remoteView = new RemoteViews(getPackageName(), R.layout.notification_test);
notification.contentView = remoteView;
最后添加设置好的notification即可,其中R.string.app_name为这个通知事件的ID,为后面移除这个通知用的。
mNotifyManager.notify(R.string.app_name, notification);
移除:
notifyManager.cancel(R.string.app_name);
/** * Android添加Notification的代码片断,防止忘记了 * Yao.GUET * blog: http://blog.youkuaiyun.com/Yao_GUET */ public void addNotify() { // TODO Auto-generated method stub NotificationManager mNotifyManager = (NotificationManager)getSystemService( Context.NOTIFICATION_SERVICE); // public Notification (int icon, CharSequence tickerText, long when) // icon will show on status bar // tickerText is the display content on status bar. Notification notification = new Notification(R.drawable.icon, null, System.currentTimeMillis()); // set the notification defaults, // DEFAULT_ALL=DEFAULT_VIBRATE | DEFAULT_LIGHTS | DEFAULT_SOUND notification.defaults = Notification.DEFAULT_ALL; // set the notification flags // FLAG_ONGOING_EVENT means notification will disaplay under ongoing // other will display under Notifications notification.flags |= Notification.FLAG_ONGOING_EVENT; // after a 100ms delay, vibrate for 250ms, pause for 100 ms and // then vibrate for 500ms. // notification.vibrate = new long[] { 100, 250, 100, 500}; // set the intent, it will open when click the notification on expended status bar // intent.putExtra("img", R.drawable.icon); Intent intent = new Intent(mContext, NotificationCancelAll.class); PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0); // set the title and content show in notification panel // pendingIntent is onClick event notification.setLatestEventInfo(mContext, "NotificationTitle", "Notification Content!", pendingIntent); // custom the notification view in expended status bar // RemoteViews remoteView = new RemoteViews(getPackageName(), R.layout.notification_test); // notification.contentView = remoteView; // add the notification // here use R.string.app_name as the notification id, // cause it is unique integer in your app, meanwhile it could be any int you want. mNotifyManager.notify(R.string.app_name, notification); }