Android组件之BroadcastReceiver

来源:互联网 发布:hiv专用交友软件 编辑:程序博客网 时间:2024/05/17 07:57

1.什么是BroadcastReceiver?

BroadcastReceiver是安卓的四大组件之一,它的功能是接收系统或应用发送的广播事件。例如当开机完成后系统会产生一条广播,接收到这条广播就能实现开机启动服务的功能;当网络状态改变时系统会产生一条广播,接收到这条广播就能及时地做出提示和保存数据等操作;当电池电量改变时,系统会产生一条广播,接收到这条广播就能在电量低时告知用户及时保存进度,等等。

广播的创建需要继承android.content.BroadcastReceiver,并实现其onReceive方法代码如下:

public class MyReceiver extends BroadcastReceiver {

private static final String TAG = "MyReceiver";

@Override
public void onReceive(Context context, Intent intent) {
String msg = intent.getStringExtra("msg");
Log.i(TAG, msg);
}
}

在onReceiver()方法中我们可以获取随广播而来Intent数据,就像无线电一样包含许多信息。


2.如何注册和使用BroadcastReceiver?

(1)在manifest中注册广播接受者为静态注册,方式如下:

<receiver android:name=".MyReceiver">
        <intent-filter>
        <action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
        <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
        </receiver>

配置了以上信息之后,只要是android.intent.action.MY_BROADCAST这个地址的广播,MyReceiver都能够接收的到。注意,这种方式的注册是常驻型的,也就是说当应用关闭后,如果有广播信息传来,MyReceiver也会被系统调用而自动运行。

(2)在代码中注册为动态注册

MyReceiver receiver=new MyReceiver();IntentFilter intentFilter=new IntentFilter();intentFilter.addAction("android.intent.action.MY_PACKAGE_REPLACED");registerReceiver(receiver,intentFilter);
在实际应用中,我们在Activity或Service中注册了一个BroadcastReceiver,当这个Activity或Service被销毁时如果没有解除注册,系统会报一个异常,提示我们是否忘记解除注册了。所以,记得在特定的地方执行解除注册操作:
@Overrideprotected void onDestroy() {    super.onDestroy();    unregisterReceiver(receiver);}
3.广播接收者的生命周期。
广播接收者的生命周期非常的短,在广播接收的时候创建,在onReceiver()方法之后销毁。
不能做耗时行的工作,否则或报ANR
最好不要在广播中创建子线程,因为广播销毁后线程变成了空进程,容易呗系统杀掉
4.广播的种类。
广播分为两种:有序广播和无序广播;
有序广播:按照被接收者的优先级顺序,在被接收者中依次传播。比如有3个广播接受者A、B、C,优先级是A>B>C,这个消息依次传给A再B后C,每个接受者都有权终止这个广播,如果被终止了后面的接受者就接收不到这个广播了。此外A接收到广播后可以对对象进行操作,当广播传给B时,B可以从结果对象中获取A存入的数据。
无序广播:完全异步,逻辑上可以被任何广播接受者接收,优点效率高,缺点是不能将处理结果传递给下一个接受者,不能终止广播
5.广播的发送
有序广播:
Intent intent = new Intent();intent.setAction("...");Context.sendOrderedBroadcast(intent,null);
无序广播:
Intent intent = new Intent();
intent.setAction("...");
Context.sendBroadcast(intent);




1 0
原创粉丝点击