android之notification消息推送机制

来源:互联网 发布:ar增强现实软件 编辑:程序博客网 时间:2024/06/08 18:14

 pendingIntent字面意义:等待的,未决定的Intent。

 pendingIntent是一种特殊的Intent。主要的区别在于Intent的执行立刻的,而 pendingIntent的执行不是立刻的。pendingIntent执行的操作实质上是参数传进来的Intent的操作,但是使用 pendingIntent的目的在于它所包含的Intent的操作的执行是需要满足某些条件的。 
        主要的使用的地方和例子:通知 Notificatio的发送,短消息 SmsManager 的发送和警报器AlarmManager的执行等等。

        Android 的状态栏通知 (Notification)

        如果需要查看消息,可以拖动状态栏到屏幕下方即可查看消息。

        步骤:

        1  获取通知管理器 NotificationManager ,它也是一个系统服务

        2  建立通知 Notification notification = new Notification(icon, null, when);

        3  为新通知设置参数 ( 比如声音,震动,灯光闪烁 )

        4  把新通知添加到通知管理器

        发送消息的代码如下:

 // 获取通知管理器

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)

        int icon = android.R.drawable.stat_notify_chat;

        long when = System.currentTimeMillis();// 通知发生的时间为系统当前时间

        // 新建一个通知,指定其图标和标题

        Notification notification = new Notification(icon, null, when);// 第一个参数为图标 , 第二个参数为短暂提示标题 , 第三个为通知时间

        notification.defaults = Notification.DEFAULT_SOUND;// 发出默认声音

        notification.flags |= Notification.FLAG_AUTO_CANCEL;// 点击通知后自动清除通知

        Intent openintent = new Intent(this, OtherActivity.class);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, openintent, 0);/ / 当点击消息时就会向系统发送openintent 意图

        notification.setLatestEventInfo(this, “ 标题 ”, “ 我是内容 ", contentIntent);

        mNotificationManager.notify(0, notification);// 第一个参数为自定义的通知唯一标识

 

        重点是 setLatestEventInfo( ) 方法的最后一个参数!!!!它是一个 PendingIntent!!!!!!!!!

        这里使用到了 PendingIntent(pend 本意是待定,不确定的意思 )

        PendingIntent 可以看作是对 Intent 的包装。 PendingIntent 主要持有的信息是它所包装的 Intent 和当前Application 的 Context 。正由于 PendingIntent 中保存有当前 Application 的 Context ,使它赋予带他程序一种执行的 Intent 的能力,就算在执行时当前 Application 已经不存在了,也能通过存在 PendingIntent 里的 Context 照样执行 Intent 。

 

        PendingIntent 的一个很好的例子:

        SmsManager 的用于发送短信的方法:

        sendTextMessage(destinationAddress, scAddress, text, sentIntent, deliveryIntent);

        第一个参数: destinationAddress  对方手机号码

        第二个参数: scAddress  短信中心号码   一般设置为空

        第三个参数: text  短信内容

        第四个参数: sentIntent 判断短信是否发送成功,如果你没有 SIM 卡,或者网络中断,则可以通过这个 itent 来判断。注意强调的是“发送”的动作是否成功。那么至于对于对方是否收到,另当别论


0 0
原创粉丝点击