作者:刘昊昱

博客:http://blog.csdn.net/liuhaoyutz

一、BroadcastReceiver机制概述

Broadcast Receiver是Android的一种“广播发布/消息接收”机制,或者说的更准确一些,是一种“监听”机制。作为广播发布者的应用程序,可以在不知道谁(如果有的话)将接收这个广播消息的情况下发出一个广播消息(广播的消息实际上就是一个Intent对象)。而消息接收者可以指定自己将接收哪些消息(通过使用intent-filter),如果出现了他指定的消息,消息接收者就会被调用对消息进行处理。

要发出一个广播消息,可以创建一个Intent对象,并调用sendBroadcast()方法将Intent对象做为消息广播出去。

广播消息的接收是通过继承BroadcastReceiver类来实现的,我们需要实现onReceive()函数,在该函数中完成对消息(即Intent对象)的处理。

二、自定义广播消息

下面来看一个例子程序,该程序演示怎样自定义一个广播消息并发送出去,同时也演示了怎样接收指定消息并处理,该程序运行效果如下:

先来看主布局文件,其内容如下:

<?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:textSize="20dp"
android:text="@string/hello" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:onClick="onButtonClick"
android:textSize="20dp"
android:text="发送消息" /> </LinearLayout>

下面来看主Activity文件,其内容如下:

package com.liuhaoyu;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View; public class MainActivity extendsActivity {
privatestatic final String MY_ACTION="com.liuhaoyu.broastcast.action.MY_ACTION"; /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
} public void onButtonClick(View v) {
Intent intent=newIntent();
intent.setAction(MY_ACTION);
intent.putExtra("msg","Broadcast Receiver测试");
sendBroadcast(intent);
}
}

当点击按钮时,创建一个广播消息(即Intent对象),指定该消息对应的Action是MY_ACTION,通过调用sendBroadcast()函数将消息广播出去。

下面来看该程序自定义的BraodcastReceiver:

package com.liuhaoyu;

importandroid.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast; public class BroadcastReceiverTestextends BroadcastReceiver { @Override
publicvoid onReceive(Context arg0, Intent arg1) {
//TODO Auto-generated method stub
Stringmsg=arg1.getStringExtra("msg");
Toast.makeText(arg0,msg, Toast.LENGTH_LONG).show();
} }

可以看到,我们继承了BroadcastReceiver类,并实现了onReceiver()函数,该函数中对消息的处理就是弹出一个消息提示。

下面程序在AndroidManifest.xml文件中声明BroadcastReceiverTest,并通过intent-filter指定监听MY_ACTION消息:

        <receiver android:name=".BroadcastReceiverTest">
<intent-filter>
<action android:name="com.liuhaoyu.broastcast.action.MY_ACTION"/>
</intent-filter>
</receiver>

三、接收系统预定义广播消息

Android系统提供了一些预定义的广播消息,Android官方文档上关于消息(即Intent对象)对应的Action描述如下:

These are the currentstandard actions that Intent defines for receiving broadcasts (usually through registerReceiver(BroadcastReceiver,IntentFilter) ora <receiver> tag in a manifest).

·        ACTION_TIME_TICK

·        ACTION_TIME_CHANGED

·        ACTION_TIMEZONE_CHANGED

·        ACTION_BOOT_COMPLETED

·        ACTION_PACKAGE_ADDED

·        ACTION_PACKAGE_CHANGED

·        ACTION_PACKAGE_REMOVED

·        ACTION_PACKAGE_RESTARTED

·        ACTION_PACKAGE_DATA_CLEARED

·        ACTION_UID_REMOVED

·        ACTION_BATTERY_CHANGED

·        ACTION_POWER_CONNECTED

·        ACTION_POWER_DISCONNECTED

·        ACTION_SHUTDOWN

下面看一个接收系统预定义的BOOT_COMPLETE广播消息的例子,当Android启动起来后,会广播BOOT_COMPLETE消息,我们的应用程序声明监听该消息,所以每次Android启动起来后,我们的应用程序就会做出对该消息的响应,怎样响应就是我们在onReceiver()函数中实现的,这个程序的响应是播放一段音乐,弹出一个提示信息,并打印LOG信息。该程序运行效果如下:

下面是LogCat中显示的LOG信息:

我们先来看主布局文件:

<?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" /> </LinearLayout>

没有什么特殊的,就是系统自动生成的,我们不做任何改变。

下面看主Activity文件,其内容如下:

package com.liuhaoyu;

import android.app.Activity;
import android.os.Bundle; public class MainActivity extendsActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}

也是系统自动生成的,不做任何改变。

下面就是重点了,即我们的BroadcastReceiver的实现:

package com.liuhaoyu;

importandroid.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.util.Log;
import android.widget.Toast; public class BootReceiver extendsBroadcastReceiver {
@Override
publicvoid onReceive(Context context, Intent intent) {
Log.e("BootReceiver","received BOOT_COMPLETED intent!");
MediaPlayer.create(context,R.raw.enter).start();
Toast.makeText(context,"BroadcastReceiver: " + intent.getAction(),Toast.LENGTH_SHORT).show();
}
}

可以看到,我们继承了BraodcastReceiver类,实现了onReceiver()函数,在该函数中,打印一条LOG信息,播放一段音乐,并弹出一个提示信息,这就是我们的应用程序接收到指定广播消息后的处理。

有了BroadcastReceiver,还有一个重要的任务是声明我们的应用程序监听哪些消息,这个工作是在AndroidManifest.xml文件中完成的,在系统默认内容之外,添加了两处内容:

一是声明BroadcastReceiver,同时通过intent-filter指定监听BOOT_COMPLETED消息:

        <receiver android:name=".BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>

二是指定权限:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

Android应用开发学习笔记之BroadcastReceiver的更多相关文章

  1. Android应用开发学习笔记之播放音频

    作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Android支持常用音视频格式文件的播放,本文我们来学习怎样开发Android应用程序对音视频进行操作. Andr ...

  2. android移动开发学习笔记(二)神奇的Web API

    本次分两个大方向去讲解Web Api,1.如何实现Web Api?2.如何Android端如何调用Web Api?对于Web Api是什么?有什么优缺点?为什么用WebApi而不用Webservice ...

  3. Android应用开发学习笔记之事件处理

    作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Android提供的事件处理机制分为两类:一是基于监听的事件处理:二是基于回调的事件处理.对于基于监听的事件处理,主 ...

  4. Android应用开发学习笔记之Intent

    作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Intent是什么呢?来看Android官网上的定义: An intent is an abstractdescri ...

  5. Android应用开发学习笔记之AsyncTask

    作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz 在上一篇文章中我们学习了多线程和Handler消息处理机制,如果有计算量比较大的任务,可以创建一个新线程执行计算工作 ...

  6. [Android游戏开发学习笔记]View和SurfaceView

    本文为阅读http://blog.csdn.net/xiaominghimi/article/details/6089594的笔记. 在Android游戏中充当主要角色的,除了控制类就是显示类.而在A ...

  7. Android应用开发学习笔记之Fragment

    作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Fragment翻译成中文就是“碎片”.“片断”的意思,Fragment通常用来作为一个Activity用户界面的一 ...

  8. Android应用开发学习笔记之菜单

    作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Android中的菜单分为选项菜单(OptionMenu)和上下文菜单(Context Menu).通常使用菜单资源 ...

  9. Android应用开发学习笔记之多线程与Handler消息处理机制

    作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz 和JAVA一样,Android下我们可以通过创建一个Thread对象实现多线程.Thread类有多个构造函数,一般通 ...

随机推荐

  1. Qt的信号槽,一个老MFC的经验

    最近在利用闲暇时间研究Qt,大概有3周了,看过了官网的white paper并浏览了一遍<C++ GUI Programming with Qt 4, 2nd Edition>.总的来说, ...

  2. cocos2d-x游戏开发系列教程-超级玛丽07-CMGameMap(四)-马里奥平移

    上一篇博文提到,程序如何获取键盘输入,也就是D键按下,程序获取到前进指令,那么获取到前进指令之后,马里奥是如何前进的呢,这篇文章我们重点讨论这个问题. 马里奥的移动,依旧是在帧刷新函数中,这个调用过程 ...

  3. Windows Azure 社区新闻综述(#76 版)

    欢迎查看最新版本的每周综述,其中包含有关云计算和 Windows Azure 的社区推动新闻.内容和对话.以下是本周的亮点. 文章.视频和博客文章 ·   更新 Windows Azure 中的 SQ ...

  4. 11427 - Expect the Expected(概率期望)

    11427 - Expect the Expected Some mathematical background. This problem asks you to compute the expec ...

  5. Spout的实现步骤

    Spout的实现步骤: ·        对文件的改变进行分开的监听,并监视文件夹下有无新日志文件加入. ·        在数据得到了字段的说明后,将其转换成tuple. ·        声明Sp ...

  6. Struts+Tomcat搭建

    Struts+Tomcat搭建 tomcat使用(服务器端开发): 如果要安装Tomcat需要进行的配置:tomcat安装在c: \Tomcat CATALINA_HOME变量值设为: H:\Prog ...

  7. python读写xml

    来自http://blog.csdn.net/liuyuehui110/article/details/7287897 备份防止链接失效 一.XML的读取. 在 NewEdit 中有代码片段的功能,代 ...

  8. Filter学习

    在这之前一直对filter感到陌生,有点细思极恐的感觉--终于下定决心来学习一下,欢迎拍砖-- Filter的主要作用是实现对HttpServletRequest的预处理,也可以对HttpServle ...

  9. BFS 、DFS 解决迷宫入门问题

    问题 B: 逃离迷宫二 时间限制: 1 Sec  内存限制: 128 MB提交: 12  解决: 5[提交][状态][讨论版] 题目描述 王子深爱着公主.但是一天,公主被妖怪抓走了,并且被关到了迷宫. ...

  10. Codeforces Round #312 (Div. 2)

    好吧,再一次被水题虐了. A. Lala Land and Apple Trees 敲码小技巧:故意添加两个苹果树(-1000000000, 0)和(1000000000, 0)(前者是位置,后者是价 ...