作者:刘昊昱

博客: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. 【学习】leader特别忙工作到晚上11点左右,组员7点左右下班了,作为leader怎么办?

    Ø  leader先将自己做的事情罗列出来,选出不属于leader当前职责的工作内容. Ø  将不属于leader职责内容的部分授权给组员(承担更多的责任,职责). Ø  授权时,先考察组员的能力和了 ...

  2. cocos2dx进阶学习之屏幕适配

    背景 在学习cocos2dx时,我们在main函数中发现一句代码, #include "main.h" #include "AppDelegate.h" #in ...

  3. JFreeChart画折线图

    请见Github博客: http://wuxichen.github.io/Myblog/htmlcss/2014/09/01/JFreechartLinechart.html

  4. 【JUnit4.10源码分析】5 Statement

    假设要评选JUnit中最最重要的类型.或者说核心,无疑是org.junit.runners.model.Statement.Runner等类型看起来热闹而已. package org.junit.ru ...

  5. Linux下的定时器

    以下摘自linux下的man文件:(man  getitimer) #include  <sys/time.h> int  getitimer(int which,  struct iti ...

  6. C#学习之-----再论委托

    using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threa ...

  7. [Swust OJ 352]--合并果子(贪心+队列模拟)

    题目链接:http://acm.swust.edu.cn/problem/352/ Time limit(ms): 1000 Memory limit(kb): 65535   Description ...

  8. 转:DNS拾遗

    最近帮朋友注册域名配置主机,碰到一些DNS上的一些概念,惭愧于有一些东西已经忘记是啥意思,于是决定重新学习一下DNS方面的基本概念. 常用概念: TTL: TTL为Time to live的缩写,网络 ...

  9. matlab绘图方法汇总

    Matlab画图 强大的画图功能是Matlab的特点之中的一个,Matlab提供了一系列的画图函数,用户不须要过多的考虑画图的细节,仅仅须要给出一些基本參数就能得到所需图形,这类函数称为高层画图函数. ...

  10. Thinkphp里import的几个使用方法介绍

    以下附上import的几个使用方法介绍 1.使用方法一 import('@.Test.Translate'); @,表示项目根文件夹.假定根文件夹是:App/ 导入类库的路径是:App/Lib/Tes ...