BroadcastReceiver与activity,service有完整的生命周期不同,BroadcastReceiver本质上是一系统级别的监听器,专门负责监听各程序发出的broadcast.与程序级别的监听器不同的是,例如OnXxxListener(),这些监听器运行在指定程序进程中,当程序退出时,oNXxxListener也随之关闭。但BroadcastReceiver属于系统级别的监听器,拥有自己的进程,只要存在与之匹配的Intent被广播出来,BroadcastReceiver总会被激发。
  指定该BroadcastReceiver能匹配的Intent有两种方式:
  1.使用代码指定:
    调用BroadcastReceiver的context的registerReceiver(BroadcastReceiver recevier,IntentFilter filter).例如:
    IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
        IncomingSMSRecevier receiver = new IncomingSMSRecevier();
        registerReceiver(receiver, filter);
  2.在AndroidManifest.xml文件中配置
   <receiver android:name=".IncomingSMSRecevier ">
            <intent-filter >
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
        </receiver>
  注意:如果BroadcastReceiver方法不能在10秒内执行完成,Android会认为该程序无响应,不要在BroadcastReceiver的OnReceiver方法内执行一些耗时的操作,否则会弹出ANR(Application No Response)的对话框。
 例子,发送一个普通广播,接收广播的例子:
 step1: main.xml
 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <Button android:id="@+id/send"
        android:text="点击发送广播"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>

 
step2:创建发送广播的activity为BroadCastMain:
package com.lp.ecjtu;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class BroadCastMain extends Activity {
    private Button sendBtn;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        sendBtn = (Button) findViewById(R.id.send);
        sendBtn.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                //设置intent的Action属性
                intent.setAction("com.lp.action.WELCOME_BROADCAST");
                intent.putExtra("msg", "消息");
                //发送广播,使用intent发送一条广播
                sendBroadcast(intent);
            }
        });
    }
}

 
step3:创建接收广播的类MyReceiver.java
 
package com.lp.ecjtu;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

/** 当符合该MyReceiver的广播出现时,onReceive方法会被触发,从而显示广播所携带的消息 */
public class MyReceiver extends BroadcastReceiver{

@Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Toast.makeText(context, "接受到的Intent的Action是:"
                        +intent.getAction()
                        +"\n消息的内容为:"+intent.getStringExtra("msg")
                , Toast.LENGTH_LONG).show();
    }
    
}

step4:别忘了:在AndroidManifest.xml中增加:
<!-- 指定该BroadcastReceiver所响应的Intent的Action -->
        <receiver android:name=".MyReceiver">
            <intent-filter >
                <action android:name="com.lp.action.WELCOME_BROADCAST"/>
            </intent-filter>
        </receiver>
 
step5运行结果:
广播又可以分为“普通广播”和“有序广播”,上面介绍的普通广播,下面介绍有序广播:
  普通广播和有序广播各自的优缺点:
  普通广播是完全异步的,可以在同一时刻(逻辑上)被所有接收者接收到,优点效率比较高,缺点接收者不能将处理结果传递给下一个接收者,并且无法终止广播Intent的传播。
  有序广播是按照接收者声明的优先级别,被接收者依次接收广播。如:A的级别高于B,B的级别高于C,那么,广播首先传给A,再传给B,最后传给 C 。优先级别在<intent-filter>的android:priority属性中声明,数值越大优先级别越高,取值范围:-1000到 1000,优先级别也可以调用IntentFilter对象的setPriority()进行设置 。
  有序广播的接收者可以终止广播Intent的传播,广播Intent的传播一旦终止,后面的接收者就无法接收到广播。另外,有序广播的接收者可以将数据传递给下一个接收者,如:A得到广播后,可以往它的结果对象中存入数据,当广播传给B时,B可以从A的结果对象中得到A存入的数据。
  好吧知道了有序广播的原理后,我们来看一个例子:
step1:main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <Button android:id="@+id/send"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="点击发送有序广播"
        />
</LinearLayout>

 
step2 发送有序广播:
package com.lp.ecjtu;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class BroadcastSorted extends Activity {
    private Button sendbtn;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        sendbtn = (Button) findViewById(R.id.send);
        sendbtn.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction("com.lp.action.WELCOME_BROADCAST");
                    intent.putExtra("msg", "消息");
                    //发送有序广播
                    sendOrderedBroadcast(intent, null);
            }
        });   
    }
}

 
step3 第一个BroadcastReceiver:
package com.lp.ecjtu;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver{

@Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Toast.makeText(context, "接收到的intent的action为:"+intent.getAction()
                +"\nintent的消息的内容为:"+intent.getStringExtra("msg"), Toast.LENGTH_LONG).show();
        //创建一个Bundle对象
        Bundle mBundle = new Bundle();
        mBundle.putString("first", "第一个BroadcastReceiver存入的消息");
        //将Bundle放入结果中
        setResultExtras(mBundle);
        //取消broadcast的继续传播
        //abortBroadcast();
    }

}
step4第二个BroadcastReceiver

 
package com.lp.ecjtu;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class MyReciever2 extends BroadcastReceiver{

@Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = getResultExtras(true);
        //解析前一个BroadcastReceiver所存入的key为first的消息
        String first = bundle.getString("first");
        Toast.makeText(context, "第一个Broadcast存入的消息为:"+first,500000).show();
    }

}
step5

AndroidManifest.java
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.lp.ecjtu"
    android:versionCode="1"
    android:versionName="1.0" >

<uses-sdk android:minSdkVersion="10" />

<application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".BroadcastSorted"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".MyReceiver" >
            <intent-filter android:priority="20">
                <action android:name="com.lp.action.WELCOME_BROADCAST"/>
            </intent-filter>
        </receiver>
        <receiver android:name=".MyReciever2" >
            <intent-filter android:priority="0">
                <action android:name="com.lp.action.WELCOME_BROADCAST"/>
            </intent-filter>
        </receiver>
    </application>
    
</manifest>

 
step6效果图:分析:
该程序中包含两个BroadcastReceiver,分别为MyReciever,MyReciever2,由于MyReciever的优先级高,则如果加上abortBroadcast();将阻止消息的传播,不会传到MyReciever2,如果abortBroadcast();注释掉,则程序MyReciever2的OnReceive方法可以触发,并解析得到MyReciever存入结果中的key为first的消息。结果图:
  MyReciever中接受到的内容:
  
 MyReciever2:
 
其他广播Intent如
<action android:name="android.intent.action.BATTERY_CHANGED"/>电池电量变化广播Intent
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>短信
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>电话

广播接收者BroadcastReceiver的更多相关文章

  1. 广播接收者 BroadcastReceiver 示例-1

    广播机制概述 Android广播分为两个方面:广播发送者和广播接收者,通常情况下,BroadcastReceiver指的就是广播接收者.广播作为Android组件间的通信方式,可以使用的场景如下: 1 ...

  2. Android系统编程入门系列之广播接收者BroadcastReceiver实现进程间通信

    在前边几篇关于Android系统两个重要组件的介绍中,界面Activity负责应用程序与用户的交互,服务Service负责应用程序内部线程间的交互或两个应用程序进程之间的数据交互.看上去这两大组件就能 ...

  3. Android - 广播接收者 - BroadcastReceiver

    BroadcastReceiver 介绍: 广播是一种广泛运用的在应用程序之间传输信息的机制 .而 BroadcastReceiver 是对发送出来的广播 进行过滤接收并响应的一类组件 接受一种或者多 ...

  4. 广播接收者 BroadcastReceiver 示例-2

    BaseActivity /**所有Activity的基类*/ public class BaseActivity extends Activity {     @Override     prote ...

  5. Android中广播接收者BroadcastReceiver详解

    1. 接收系统的广播步骤 (1)  新建一个类继承BroadcastReceiver 以监听sd卡状态的广播接收者为例 public class SdCardBroadcastReceiver ext ...

  6. Android学习笔记_19_广播接收者 BroadcastReceiver及其应用_窃听短信_拦截外拨电话

    一.广播接收者类型: 广播被分为两种不同的类型:“普通广播(Normal broadcasts)”和“有序广播(Ordered broadcasts)”. 普通广播是完全异步的,可以在同一时刻(逻辑上 ...

  7. 广播接收者 BroadcastReceiver

    1. 分为动态注册和静态注册, 静态注册在清单文件里配置即可.动态创建为代码手动添加. 在锁屏广播中, 使用静态创建消息接受不成功, 原因未知. 动态即可. 代码如下: 2. 创建类, 继承与Broa ...

  8. 广播发送者&广播接收者介绍

    1.广播接收者 广播接收者简单地说就是接收广播意图的Java类,此Java类继承BroadcastReceiver类,重写: public void onReceive(Context context ...

  9. Android(java)学习笔记175:BroadcastReceiver之 外拨电话的广播接收者

    首先我们示例工程一览表如下: 1.首先我们还是买一个收音机,定义一个OutCallReceiver继承自BroadcastReceiver,onReceive()方法中定义了监听到广播,要执行的操作: ...

随机推荐

  1. 【转】C#中Invoke的用法

    在多线程编程中,我们经常要在工作线程中去更新界面显示,而在多线程中直接调用界面控件的方法是错误的做法,Invoke 和 BeginInvoke 就是为了解决这个问题而出现的,使你在多线程中安全的更新界 ...

  2. CentOS 7 + nginx + uwsgi + web2py (502 bad gateway nginx)

    Web2py开发包中自带的setup-web2py-nginx-uwsgi-centos64.sh脚本, 只能运行在CentOS 6.4中使用, 如果直接在CentOS 7 中使用该脚本布署后, 访问 ...

  3. ssh公钥免密码登录

    1,生成公钥 ssh-keygen -t rsa 2,上传至服务器 将个人电脑的公钥添加到服务器 cat id_rsa.pub >> ~/.ssh/authorized_keys 3,本地 ...

  4. wpa_supplicant 使用

    (1)通过adb命令行,可以直接打开supplicant,从而运行wpa_cli,可以解决客户没有显示屏而无法操作WIFI的问题,还可以避免UI的问题带到driver.进一步来说,可以用在很多没有键盘 ...

  5. .Net开源数据库设计工具Mr.E For Linq (EF 6.1) 教程(二)级联删除和触发器

    1.建立级联删除 Mr.E的级联删除并非数据库自带那个级联删除,而是Mr.E自带的,所以它能触发你C#里面编写的触发器. 首先,建立级联删除关系,如下图有两个表,UserInfo和UserDocume ...

  6. 学习jax-ws(一)

    1.生成文件时提示class not find ,需要加个cp .,这样就行了 E:\mylearn\learn_webservice\learnJax-ws\bin>wsgen -cp . w ...

  7. [uwp开发]数据绑定那些事(2)

    接着上一篇来侃. 二.实体到控件之间的绑定 这儿不知道用实体这个词恰不恰当,凑活着理解就行了.他可以是一个类实例,也可以是一个集合. 所以,相应的我们就引入两个Demo,第一个介绍用简单的类作为作为数 ...

  8. dmucs与distcc

    之前配置distcc没有考虑负载均衡这一项,现在考虑使用dmucs实现distcc的负载均衡 官方手册 http://dmucs.sourceforge.net/ 使用官方手册编译会报错,等解决问题后 ...

  9. VC6.0装了visual assist x回车键不能补全代码的解决方法

    问题:VC6.0装了visual assist x补全代码具体怎么用?         输入字母后会像输入法那样出现一个菜单        但是怎么选择菜单里面的内容呢?        什么 回车  ...

  10. 【环境】VS2013和MATLAB相互调用混合编程

    Visual Studio和MATLAB混合编程,有两种方法: 1 MATLAB调用C程序: 2 VS调用MATLAB(目前见到的都是VS,其他编译器如codeblocks,或不提供这项功能): 前一 ...