Andorid notification 通知使用

Posted on 2011-09-05 12:02  矛盾体  阅读(168)  评论(0)    收藏  举报

在有消息通知的时候,我们经常用Toast或者Notification,如果是要用到长时间显示(如程序后台下载),用Notification就最合适不过了.

Android就有一套很好的通知机制来让我们操作,Android的这一创新的UI组件赢得了不少开发者的好评,连Apple也在模仿.

而使用Notification也非常简单.

Notification 使用流程;

1)初始化Notification和NotificationManager

notificationManager=(NotificationManager)

                getSystemService(

                        Context .NOTIFICATION_SERVICE);

        

         notification =new Notification(R.drawable.sys_board_choose

              ,"系统通知",System.currentTimeMillis());

Notification的三个参数分别是图片,通知文本和时间.

2)设置Notification的标志

notification.flags=Notification.FLAG_AUTO_CANCEL;

//      1.FLAG_AUTO_CANCEL:在用户查看通知信息后自动关闭通知;

//      2.FLAG_INSISTENT:在用户响应之前一直重复发送声音;

//      3.FLAG_ONGOING_EVENT:放置在“正在运行”栏目中,表示程序正在运行,可见状态,或是后台运行;

//      4.FLAG_NO_CLEAR:查看通知后不会自动取消,对一直进行中的通知非常有用。

        

3)开始写Inent

 intent =new Intent(this,TargetActivity.class);

  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);//可选

4)用PendIngIntent封装Intent

Intent:意图,即告诉系统我要干什么,然后系统根据这个Intent这个对应的事,如startActivity相当于发送消息,而Intent是消息的内容.

PendingIntent:包装Intent,Intent是我们直接使用startActivity,startService,startBroadcast来启动某项工作意图.

而某些时候,我而是希望当程序或者系统达到某一条件是才发送Intent.

所以用Pending来封装,也因为setLatestEventInfo方法也是需要使用PendingIntent作为参数之一

 pendingIntent =PendingIntent.getActivity(

                context,requestCode,intent,PendingIntent.FLAG_UPDATE_CURRENT

                );

    //  PendingIntent.FLAG_UPDATE_CURRENT  表示如果该描述的PendingIntent已存在,

    //  则改变已存在的PendingIntent的Extra数据为新的PendingIntent的Extra数据。     

5)讲PendingIntent配置到Notification

     notification.setLatestEventInfo(context, "系统通知标题", "通知内容", pendingIntent );

6)再启用NotificationManager.notify方法

 notificationManager.notify(id,notification);

此id对应唯一的通知标志.

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3