android PendingIntent介绍

来源:互联网 发布:php长连接框架 编辑:程序博客网 时间:2024/06/14 15:59

本文主要介绍PendingIntent的作用和举例以及和Intent的区别,本文中代码见AndroidDemo@GoogleCode。

1、PendingIntent作用

根据字面意思就知道是延迟的intent,主要用来在某个事件完成后执行特定的Action。PendingIntent包含了Intent及Context,所以就算Intent所属程序结束,PendingIntent依然有效,可以在其他程序中使用。
常用在通知栏及短信发送系统中。

PendingIntent一般作为参数传给某个实例,在该实例完成某个操作后自动执行PendingIntent上的Action,也可以通过PendingIntent的send函数手动执行,并可以在send函数中设置OnFinished表示send成功后执行的动作。

2、PendingIntent举例

a. 系统通知栏

复制代码
NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
int icon = android.R.drawable.stat_notify_chat;
long when = System.currentTimeMillis() + 2000;
Notification n = new Notification(icon, “通知栏demo提醒”, when);
n.defaults = Notification.DEFAULT_SOUND;
n.flags |= Notification.FLAG_AUTO_CANCEL;

Intent openintent = new Intent(this, DemoList.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, openintent, PendingIntent.FLAG_CANCEL_CURRENT);
n.setLatestEventInfo(this, “通知栏demo提醒title”, “通知栏demo提醒text”, pi);
nm.notify(0, n);

复制代码

setLatestEventInfo表示设置点击该通知的事件

b. 短信系统举例

短信系统举例代码

以上的两个PendingIntent sentPI和deliveredPI将分别在短信发送成功和对方接受成功时被广播

3、Intent和PendingIntent的区别

a. Intent是立即使用的,而PendingIntent可以等到事件发生后触发,PendingIntent可以cancel
b. Intent在程序结束后即终止,而PendingIntent在程序结束后依然有效
c. PendingIntent自带Context,而Intent需要在某个Context内运行
d. Intent在原task中运行,PendingIntent在新的task中运行

参考:

http://developer.android.com/reference/android/app/PendingIntent.html

http://blog.163.com/hnaylgqde@126/blog/static/11031970220113955852106/

0 0
原创粉丝点击