android PendingIntent学习

[color=red]Intent是一个意图,一个描述了想要启动一个Activity、Broadcast或是Service的意图。[/color]它主要持有的信息是它[b]想要启动的组件[/b](Activity、Broadcast或是Service),在开发操作中,需要通过[color=red]startActivity ,startService或sendBroadcast[/color]方法来启动这个意图执行某些操作。

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

[color=red]PendingIntent可以认为是对Intent的包装[/color],执行这个 PendingIntent时,[color=red]间接地调用里面的Intent[/color],即外部App延时执行PendingIntent中描述的Intent及其最终行为,PendingIntent主要持有的信息是它所包装的Intent和当前App Context,[color=red]即使当前App已经不存在了,也能通过存在于PendingIntent里的 Context来执行Intent。[/color]当你把PendingIntent递交给别的程序进行处理时,[color=red]PendingIntent仍然拥有PendingIntent原程序所拥有的权限[/color],当你从系统取得一个PendingIntent时,一定要非常小心才行,比如,通常,如果Intent目的地是你自己的component(Activity/Service/BroadcastReceiver)的话,你最好采用在Intent中显示指定目的component名字的方式,以确保Intent最终能发到目的,否则Intent最后可能不知道发到哪里了。

可以这样理解:当你想在Aactivity中启动另一个Bactivity,那么你可以选择两种情况[[color=red]立即启动或延时启动[/color]]:
1.通过intent配置需要启动的Bactivity,然后调用startActivity()方法,让他立即执行启动操作,跳转过去
2.另一种情况是,你虽然想启动另一个Bactivity,可是你并不想马上跳转到Bactivity页面,你想静等5分钟之后再跳转到Bactivity,那么你可以通过PendingIntent来实现[[color=red]当然实现方式有很多啦,这里仅是想说明PendingIntent与intent的区别[/color]],PendingIntent可以包装第1步中的intent,然后通过AlarmManager这个定时器,[color=red]定制5分钟之后启PendingIntent,实现这种延时操作[/color]。

[size=medium][b]如何获得一个PendingIntent呢[/b][/size]
1.可以通过[color=red]PendingIntent.getActivity(Context context, int requestCode, Intent intent, int flags)[/color]系列方法从系统取得一个用于启动一个Activity的PendingIntent对象

2.可以通过[color=red]PendingIntent.getService(Context context, int requestCode, Intent intent, int flags)[/color]方法从系统取得一个用于启动一个Service的PendingIntent对象

3.可以通过[color=red]PendingIntent.getBroadcast(Context context, int requestCode, Intent intent, int flags)[/color]方法从系统取得一个用于向BroadcastReceiver的发送广播的PendingIntent对象

最后一个参数flag有如下选择:
[color=red]PendingIntent.FLAG_UPDATE_CURRENTFLAG_CANCEL_CURRENT[/color]:如果当前系统中已经存在一个相同的PendingIntent对象,那么就将先将已有的PendingIntent取消,然后重新生成一个PendingIntent对象。

[color=red]PendingIntent.FLAG_NO_CREATE[/color]:如果当前系统中不存在相同的PendingIntent对象,系统将不会创建该PendingIntent对象而是直接返回null。

[color=red]PendingIntent.FLAG_ONE_SHOT[/color]:该PendingIntent只作用一次,如果该PendingIntent对象已经触发过一次,那么下次再获取该PendingIntent并且再触发时,系统将会返回一个SendIntentException,在使用这个标志的时候一定要注意哦。

[color=red]PendingIntent.FLAG_UPDATE_CURRENT[/color]:[b]如果系统中已存在该PendingIntent对象,那么系统将保留该PendingIntent对象,但是会使用新的Intent来更新之前PendingIntent中的Intent对象数据,例如更新Intent中的Extras。这个非常有用,例如之前提到的,我们需要在每次更新之后更新Intent中的Extras数据,达到在不同时机传递给MainActivity不同的参数,实现不同的效果。[/b][color=blue]常用[/color]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值