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

Android基础 : 第二部分 – Intent接收器

2013年12月08日 ⁄ 综合 ⁄ 共 1637字 ⁄ 字号 评论关闭

Android基础 : 第二部分 - Intent接收器

http://www.fulema.com/viewthread.php?tid=4&extra=page%3D1
我们来了解一些关于Intent接收器的相关知识。

Android的Intent接收器是Android事件处理机制中的一部分,它可以进行动作的广播,因此,我们可以用它来作为事件处理器。

创建Intent接收器:
Android中定义了一个‘BroadcastReceiver’类,所有其他Intent接收器都必须继承该类,参见下例:

  1. package com.wissen.testApp.receiver;
  2. public class MyIntentReceiver extends BroadcastReceiver {
  3. @Override
  4. public void onReceive(Context context, Intent intent) {
  5.        …
  6. }
  7. }

复制代码

如上所示,我们自己创建的Intent必须重载父类的onReceive方法,onReceive方法将在Intent接收器的动作广播时被调用,因此onReceive方法是Intent接收器的入口。
Intent接收器在AndroidManifest.xml中如下配置:

  1. <receiver android:name=”.receiver.MyIntentReceiver” android:enabled=”true”>
  2. <intent-filter>
  3.        <action android:name=”com.wissen.testApp.MY_INTENT_RECEIVER” />
  4. </intent-filter>
  5. </receiver>

复制代码

不过Intent接收器也可以通过Context.registerReceiver()方法来进行动态注册,参看下例:

  1. ..
  2. MyIntentReceiver intentReceiver = new MyIntentReceiver();
  3. IntentFilter intentFilter = new IntentFilter(”com.wissen.testApp.MY_INTENT_RECEIVER”);
  4. registerReceiver(intentReceiver, intentFilter);
  5. ..

复制代码

广播Intent:
Intent可以通过Context类的sendBroadcast()方法和sendOrderedBroadcast()方法进行广播。 sendBroadcast方法将Intent一次广播到所有的Intent接收器,而sendOrderedBroadcast()方法则是依次顺序广 播。顺序广播的方式使得当前的Intent接收器可以具备一些诸如与上一个Intent接收器交换结果,或者忽略广播等能力。 AndroidManifext.xml配置文件中的<intent-filter>标签上的android:priority属性可以用来
指定Intent接收器接收广播的顺序。

接收器的生命周期:
Intent接收器只有一个生命周期相关的方法:onReceive()。接收器对象的存活区间只有在onReceive的执行期间,当该方法执行结束, 这个接收器对象就被垃圾收集器认为是不活动的对象进行收集处理掉。也正由于这个原因,在接收器对象的onReceive方法中不能处理任何异步的操作。

权限:
有时候为处理一些Intent而定义Intent接收器时需要为这些接收器指定权限。我们可以在AndroidManifest.xml文件中使 用<user-permission>标签来定义权限。如何采用动态注册Intent接收器的方式,则我们可以将权限作为 registerReceiver方法的参数传入。
要让广播Intent时的权限生效,则需要指定sendBroadcast()方法或sendOrderedBroadcast()方法的权限参数项(不能为null)。

抱歉!评论已关闭.