作者:刘昊昱

博客: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. [置顶] High Performance Canvas Game for Android

    Rule #0 为移动平台进行优化 为移动平台进行优化是十分重要的,因为移动平台的性能大概只有桌面平台的1/10左右(*1),它通常意味着: 更慢的CPU速度,这意味着不经过优化的JavaScript ...

  2. BZOJ 1677: [Usaco2005 Jan]Sumsets 求和

    题目 1677: [Usaco2005 Jan]Sumsets 求和 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 617  Solved: 344[Su ...

  3. 服务器端开发(Python/C++)-今日头条-拉勾网-最专业的互联网招聘平台

    服务器端开发(Python/C++)-今日头条-拉勾网-最专业的互联网招聘平台 服务器端开发(Python/C++)

  4. ThinkPHP - 空模块+空操作

    空操作 空操作是指系统在找不到指定的操作方法的时候,会定位到空操作(_empty)方法来执行,利用这个机制,我们可以实现错误页面和一些URL的优化. 例如,下面我们用空操作功能来实现一个城市切换的功能 ...

  5. Unbuntu 14.04 下chrome browser bookmark 显示中文乱码解决方案

    来源:http://blog.csdn.net/loveaborn/article/details/29579787 网上有人给出这个问题的解决是通过修改文件/etc/fonts/conf.d/49- ...

  6. 【集训笔记】二分图及其应用【HDOJ1068【HDOJ1150【HDOJ1151

    匈牙利算法样例程序 格式说明 输入格式: 第1行3个整数,V1,V2的节点数目n1,n2,G的边数m 第2-m+1行,每行两个整数t1,t2,代表V1中编号为t1的点和V2中编号为t2的点之间有边相连 ...

  7. Ural 1086 - Cryptography

    While preparing this problem set the jury has run into the following problem: it was necessary to se ...

  8. datetime.timedelta

    from django.utils import timezoneimport datetime timezone.now()datetime.datetime(2014, 7, 18, 9, 42, ...

  9. QTableView 添加进度条 添加按钮 TreeWidget 增删改

    http://www.cnblogs.com/li-peng/p/3961386.html http://www.cnblogs.com/li-peng/p/3961843.html http://w ...

  10. [转]CentOS下性能监测工具 dstat

    原文链接:http://www.bkjia.com/Linuxjc/935113.html 参考链接:https://linux.cn/article-3215-1.html,http://lhfli ...