---
title: "android手记之--广播接收者"
author: "xtfncel"
date: "2010-05-02T18:47:46Z"
tags: []
categories: ["移动开发"]
slug: "android"
draft: false
lastmod: "2010-05-02T18:47:46Z"
id: 657910
url: "https://xtfncel.iteye.com/blog/657910"
---

**广播接收者(BroadcastReceiver)**

 

1,什么是BroadcastReceiver?

    广播接收者（BroadcastReceiver）用于异步接收广播Intent，广播Intent的发送是通过调用Context.sendBroadcast()、Context.sendOrderedBroadcast()或者Context.sendStickyBroadcast()来实现的。通常一个广播Intent可以被订阅了此Intent的多个广播接收者所接收.

 

2,Context.startActivity()与Context.sendBroadcast()方法发送意图的区别?

    Context.startActivity()发送的意图只能被一个组件接收,当然这个组件可以是activity或Service;

    Context.sendBroadcast()发送的意图可以被订阅了此Intent的多个广播接收者所接收.只能是广播收都接收.

 

3,如何实现一个广播接收者?

要实现一个广播接收者方法如下：

第一步：继承BroadcastReceiver，并重写onReceive()方法。

public class IncomingSMSReceiver extends BroadcastReceiver {

       @Override public void onReceive(Context context, Intent intent) {

       }

}

第二步：订阅感兴趣的广播Intent，订阅方法有两种：

第一种：使用代码进行订阅

IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS\_RECEIVED");

IncomingSMSReceiver receiver = new IncomingSMSReceiver();

registerReceiver(receiver, filter);

第二种：在AndroidManifest.xml文件中的&lt;application&gt;节点里进行订阅:

&lt;receiver android:name=".IncomingSMSReceiver"&gt;

    &lt;intent-filter&gt;

         &lt;action android:name="android.provider.Telephony.SMS\_RECEIVED"/&gt;

    &lt;/intent-filter&gt;

&lt;/receiver&gt;

   

    当系统中发送出来一个意图后,系统会根据该意图的action自动去匹配系统中现有各个意图过滤intent-filter,一旦发现有匹配的广播收接者,则系统会自动调用该广播接收者的onReceive方法.那么我们就可以在这个方法做事了.

    例如:当系统收到短信时，会发出一个action名称为android.provider.Telephony.SMS\_RECEIVED的广播Intent，该Intent存放了接收到的短信内容，使用名称“pdus”即可从Intent中获取短信内容。我们就可以写一个自已的广播接收者并且action定义为android.provider.Telephony.SMS\_RECEIVED,那么当有短信收到后我们就可以在onReceive方法里面去获取短信的内容了.

    在广播接收者做的事情不宜太复杂,耗时太长.大约在系统中BroadcastReceive的生命周期约5秒.超时后将会被回收,所以如果需要在onReceive方法做复杂的业务处理进最好开起一个线程来完成工作.