前两天帮同学写了一个很小的应用程序,刚好用到通知栏。虽然使用起来很简单,但还是贴在这里备用吧,后期消息推送时会用到。
发送通知的步骤如下:
1).获取通知管理器
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
2).新建一个通知,指定其图标和标题
int icon = android.R.drawable.stat_notify_chat;
long when = System.currentTimeMillis();
//第一个参数为图标,第二个参数为标题,第三个为通知时间
Notification notification = new Notification(icon, null, when);
Intent openintent = new Intent(this, OtherActivity.class);
//当点击消息时就会向系统发送openintent意图
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, openintent, 0);
notification.setLatestEventInfo(this, “标题”, “内容", contentIntent);
mNotificationManager.notify(0, notification);
我的代码:
final NotificationManager manager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);//获取通知管理器 Notification notification=new Notification(R.drawable.ic_launcher,"警告",System.currentTimeMillis());//通知的时机 notification.flags = Notification.FLAG_AUTO_CANCEL;//点击一次通知就自动消失 PendingIntent pIntent=PendingIntent.getActivity(context,0,new Intent(context,MainActivity.class),0);//跳转到主界面 notification.setLatestEventInfo(context,"警告","本日使用屏幕已超过预设,如需取消该警告请重新设置!!!",pIntent);//通知栏显示内容 manager.notify(NOTIFY_ID, notification);//执行 ...... //取消通知栏通知 final NotificationManager manager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE); manager.cancel(NOTIFY_ID);