Notification在程序中主要起到一个通知的作用,就是我们平时下拉托盘上面可以查看的一些状态信息。
添加一个Notification只需下面几个步骤:
1、 获取Notification的服务:
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
2、 先设置好Notification的各种属性,如图表,显示信息,声音等:
int icon = R.drawable.stat_sys_call_record;
String contentTitle = getString(R.string.app_name);
String contentText = getString(R.string.notification_recording);
3、 创建和声明一个Notification:
Notification notification = new Notification(icon, contentTitle, 0);
notification.flags |= Notification.FLAG_ONGOING_EVENT; //把通知放置在"正在运行"栏目中
4、 点击Notification后要跳转的Activity设置
Intent intent = new Intent(context, SoundRecorder.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
5、 发送通知:
mNotificationManager.notify(NOTIFICATION_ID, notification);// NOTIFICATION_ID作为这个通知的一个ID号
完整的实例代码如下:
//定义相关变量
public final static int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
//定义发送通知的方法,在你想要发送通知的调用该方法
//20150128 added
private void sentNotification() {
Context context = this;
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.stat_sys_call_record;
String contentTitle = getString(R.string.app_name);
String contentText = getString(R.string.notification_recording);
Notification notification = new Notification(icon, contentTitle, 0);
notification.flags |= Notification.FLAG_ONGOING_EVENT;
Intent intent = new Intent(context, SoundRecorder.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
//added end
6、 一般情况我们会在onDestory()方法中将通知取消
mNotificationManager.cancel(NOTIFICATION_ID);//20150128 added
有些时候我们点击某个notification进入到Activity中,当前Activity正在执行某些事件时,这时候走onCreate()的话状态则得不到保存。解决方法是:
在AndroidManifest.xml文件中该Activity下添加这样一句:android:launchMode="singleInstance"
或者另外一种方式是在notification代码中添加红色的两行也可以实现。
private void setUpNotification() {
Context context = this;
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.stat_sys_call_record;
String contentTitle = getString(R.string.app_name);
String contentText = getString(R.string.notification_recording);
Notification notification = new Notification(icon, contentTitle, 0);
notification.flags |= Notification.FLAG_ONGOING_EVENT;
Intent intent = new Intent(context, SoundRecorder.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
希望我的博客能对你有用,写博客的用意是自己做一个记录和自己的知识能在某个时候帮到大家。