Notification即状态栏通知,应用场景:当一个应用程序并未退出,只是运行于后台或者被其他程序掩盖时,如程序正在运行时,用户点击了HOME键时,程序实际并没有退出,这时可以在状态栏上显示正在运行的程序,当用户点击时回到程序的运行界面。Notification还可以用于通知用户一些与程序有关的消息等。
下面就来看Notification的使用,可以在Activity中创建一个方法用于创建Notification:
private void showNotification() {
// 定义通知管理器 NOTIFICATION_SERVICE
NotificationManager notificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
// 定义系统通知
Notification notification = new Notification(R.drawable.icon, "炫壁风",
System.currentTimeMillis());
notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_NO_CLEAR;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.defaults = Notification.DEFAULT_LIGHTS;
notification.ledARGB = Color.BLUE;
notification.ledOnMS = 5000;
CharSequence contentTitle = "Android手机壁纸--炫壁风";
CharSequence contentText = "欢迎使用炫壁风";
Intent notificationIntent = new Intent();
notificationIntent.setComponent(getComponentName());
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.setClass(context, XBFActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(this, contentTitle, contentText,
contentIntent);
notificationManager.notify(0, notification);
}
然后在需要的地方调用这个方法就行了。还有一个问题就是当点击状态栏的图标后会重新创建一个Activity,并不是回到原来的Activity,解决办法是在AndroidManifest.xml中将Activity加上android:launchMode="singleTask"属性。
删除Notification:
NotificationManager notificationManager = (NotificationManager) this
.getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(0);