PendingIntent跟Intent类似,字面意思可以看作“意图”,从功能上看基本相同,他们都可以用来启动活动、服务以及发送广播等;不同点在于,Intent倾向于及时执行某个动作,而PendingIntent比Intent多了个等待的过程,它更倾向于在某个合适的实际实行指定的动作,因此可以将它简单理解成延迟执行的Intent。
根据google的API:
A description of an Intent and target action to perform with it. Instances of this class are created with getActivity(Context, int, Intent, int)
, getActivities(Context, int, Intent[], int)
, getBroadcast(Context, int, Intent, int)
, and getService(Context, int, Intent, int)
; the returned object can be handed to other applications so that they can perform the action you described on your behalf at a later time.
PendingIntent的使用方法是使用上述三个静态方法获取实例,可以根据自己的需求来选择是使用
getActivity(Context, int, Intent, int)
、 getActivities(Context, int, Intent[], int)
、 getBroadcast(Context, int, Intent, int)
, 或者getService(Context, int, Intent, int)
方法。返回的对象会传递给其他的应用让它们在一段时间后执行你所描述的行为。观察可以发现这几个方法接收的参数完全相同:第一个参数Context;第二个参数般置0;第三个参数是一个Intent对象,用于构建PendingIntent的“意图”;最后一个参数用于确定PendingIntent的行为,查阅文档可知一般有4种值可选:
,一般也是置0。FLAG_ONE_SHOT
, FLAG_NO_CREATE
, FLAG_CANCEL_CURRENT
, FLAG_UPDATE_CURRENT
, FLAG_IMMUTABLE
getBroadcast
PendingIntent getBroadcast (Context context, int requestCode, Intent intent, int flags)
Retrieve a PendingIntent that will perform a broadcast, like calling Context.sendBroadcast()
.
For security reasons, the Intent
you supply here should almost always be an explicit intent, that is specify an explicit component to be delivered to through Intent.setClass
Parameters | |
---|---|
context | Context : The Context in which this PendingIntent should perform the broadcast. |
requestCode | int : Private request code for the sender |
intent | Intent : The Intent to be broadcast. |
flags | int : May be FLAG_ONE_SHOT , FLAG_NO_CREATE , FLAG_CANCEL_CURRENT , FLAG_UPDATE_CURRENT , FLAG_IMMUTABLE or any of the flags as supported by Intent.fillIn() to control which unspecified parts of the intent that can be supplied when the actual send happens. |