现在的位置: 首页 > 综合 > 正文

activity BroadcastReceiver Service 三大组件的启动或触发

2018年06月09日 ⁄ 综合 ⁄ 共 1730字 ⁄ 字号 评论关闭

一、intent启动或触发相关对象

1、intent 意图:我想让系统去干什么

startService(intent):想告诉系统启动服务

startActivity(intent):告诉系统启动activity

sendBroadcast(intent):告诉系统发送一个广播

2、系统接到意图后怎么做:由intent意图中携带的信息决定

对startService(intent):是启动哪个服务,由意图中的action 等信息决定

对startActivity(intent):启动哪个activity,,由意图中的action 等信息决定.

sendBroadcast(intent):发个哪个广播接收器,由意图中的action 等信息决定.

3、因此,被启动的服务和活动及想接收广播的广播接收器需要注册它的意图过滤器intent-filter

如:<intent-filter android:priority="2147483647" >
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
                <action android:name="android.provider.Telephony.GSM_SMS_RECEIVED" />
            </intent-filter>

注册有静态注册和动态注册,动态注册其生命周期在该程序的生命周期。

静态注册:是程序安装时根据AndroidManifest.xml文件注册

4、启动和触发的时候,先匹配action然后匹配category等意图过滤器的元素,如果有多个匹配成功,系统会弹出对话框让用户选择。

5、启动和触发有显式和隐式:显式则直接在intent里指明activity service broadcast,隐式调用则通过意图过滤器去匹配。

二、PendingIntent启动或触发相关对象

intent英文意思是意图,pending表示即将发生或来临的事情。
PendingIntent这个类用于处理即将发生的事情

Intent 是及时启动,intent 随所在的activity 消失而消失。
PendingIntent 可以看作是对intent的包装,通常通过getActivity,getBroadcast ,getService来得到pendingintent的实例,当前activity并不能马上启动它所包含的intent,而是在外部执行 pendingintent时,调用intent的。

PendingIntent就是一个Intent的描述,我们可以把这个描述交给别的程序,别的程序根据这个描述在后面的别的时间做你安排做的事情 (By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified as if the other application was yourself,就相当于PendingIntent代表了Intent)。

例如发送短信:

SmsManager.sendTextMessage(String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent);

1)PendingIntent sentIntent:当短信发出时,成功的话sendIntent会把其内部的描述的intent广播出去

2)PendingIntent deliveryIntent:是当消息已经传递给收信人后所进行的PendingIntent广播。
当然,也可以根据获取PendingIntent实例的不同,去启动服务或活动:通过getActivity这种方式获取-》启动活动

实际上相当于执行了两个操作:1、先发短信。2、当短信发出和已经发送到接受者时,调用startService或startActivity或sendBroadcast,触发或启动相关对象

抱歉!评论已关闭.