最近一直在研究 android ,并一边研究一边做应用。其中遇到了把程序通知常驻在 Notification 栏,并且不能被 clear 掉(就像android QQ一样)的问题。经过研究实现了其功能,现把 Notification 的使用总结如下:
Notification 的使用需要导入 3 个类
1 import android.app.PendingIntent;
2 import android.app.NotificationManager;
3 import android.app.Notification;
代码示例及说明
01 NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
02 Notification n = new Notification(R.drawable.chat, "Hello,there!", System.currentTimeMillis());
03 n.flags = Notification.FLAG_AUTO_CANCEL;
04 Intent i = new Intent(arg0.getContext(), NotificationShow.class);
05 i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
06 //PendingIntent
07 PendingIntent contentIntent = PendingIntent.getActivity(
08 arg0.getContext(),
09 R.string.app_name,
10 i,
11 PendingIntent.FLAG_UPDATE_CURRENT);
12
13 n.setLatestEventInfo(
14 arg0.getContext(),
15 "Hello,there!",
16 "Hello,there,I'm john.",
17 contentIntent);
18 nm.notify(R.string.app_name, n);
下面依次对每一段代码进行分析:
1 NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
创建 NotificationManager,其中创建的 nm 对象负责“发出”与“取消” Notification。
1 Notification n = new Notification(R.drawable.chat, "Hello,there!", System.currentTimeMillis());
2 n.flags = Notification.FLAG_ONGOING_EVENT;
创建 Notification ,参数依次为:icon的资源id,在状态栏上展示的滚动信息,时间。其中创建的 n 对象用来描述出现在系统通知栏的信息,之后我们将会看到会在 n 对象上设置点击此条通知发出的Intent。
1 n.flags = Notification.FLAG_AUTO_CANCEL;
设置 n.flags 为 Notification.FLAG_AUTO_CANCEL ,该标志表示当用户点击 Clear 之后,能够清除该通知。
1 Intent i = new Intent(arg0.getContext(), NotificationShow.class);
2 i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
创建一个Intent,该Intent使得当用户点击该通知后发出这个Intent
请注意,如果要以该Intent启动一个Activity,一定要设置 Intent.FLAG_ACTIVITY_NEW_TASK 标记。
Intent.FLAG_ACTIVITY_CLEAR_TOP :如果在当前Task中,有要启动的Activity,那么把该Acitivity之前的所有Activity都关掉,并把此Activity置前以避免创建Activity的实例
Intent.FLAG_ACTIVITY_NEW_TASK :系统会检查当前所有已创建的Task中是否有该要启动的Activity的Task,若有,则在该Task上创建Activity,若没有则新建具有该Activity属性的Task,并在该新建的Task上创建Activity。更多请参见 “ (转载)Android下Affinities和Task ”
1 //PendingIntent
2 PendingIntent contentIntent = PendingIntent.getActivity(
3 arg0.getContext(),
4 R.string.app_name,
5 i,
6 PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent 为Intent的包装,这里是启动Intent的描述,PendingIntent.getActivity 返回的PendingIntent表示,此PendingIntent实例中的Intent是用于启动 Activity 的Intent。PendingIntent.getActivity的参数依次为:Context,发送者的请求码(可以填0),用于系统发送的Intent,标志位。
其中 PendingIntent.FLAG_UPDATE_CURRENT 表示如果该描述的PendingIntent已存在,则改变已存在的PendingIntent的Extra数据为新的PendingIntent的Extra数据。
这里再简要说一下 Intent 与 PendingIntent 的区别:
Intent :意图,即告诉系统我要干什么,然后系统根据这个Inten