Boardcast receiver
转载自 : http://android.yaohuiji.com/archives/727
转载自 : http://wayfarer.iteye.com/blog/586157
本讲内容: Broadcast Receiver 的使用
1、Broadcast Receiver简介
2、Broadcast Receiver接收系统自带的广播
3、自定义广播
一、Broadcast Receiver简介
Android中的四大组件是 Activity、Service、Broadcast和Content Provider。而Intent是一个对动作和行为的抽象描述,负责组件之间程序之间进行消息传递。那么Broadcast Receiver组件就提供了一种把Intent作为一个消息广播出去,由所有对其感兴趣的程序对其作出反应的机制。
二、Broadcast Receiver接收系统自带的广播
我们做一个例子,功能是在系统启动时播放一首音乐。
1、建立一个项目Lesson21_BroadcastReceiver,拷贝一首音乐进res/raw目录
2、建立HelloBroadcastReceiver.java 内容如下:
01
|
package android.basic.lesson21;
|
02
|
03
|
import android.content.BroadcastReceiver;
|
04
|
import android.content.Context;
|
05
|
import android.content.Intent;
|
06
|
import android.media.MediaPlayer;
|
07
|
import android.util.Log;
|
08
|
09
|
public class HelloBroadReciever extends BroadcastReceiver {
|
10
|
11
|
//如果接收的事件发生
|
12
|
@Override
|
13
|
public void onReceive(Context context, Intent intent) {
|
14
|
//则输出日志
|
15
|
Log.e( "HelloBroadReciever" , "BOOT_COMPLETED!!!!!!!!!!!!!!!!!!!!!!!!!" );
|
16
|
Log.e( "HelloBroadReciever" , "" +intent.getAction());
|
17
|
18
|
//则播放一首音乐
|
19
|
MediaPlayer.create(context, R.raw.babayetu).start();
|
20
|
}
|
21
|
}
|
3、在AndroidManifest.xml中注册此Receiver :
01
|
<? xml version = "1.0" encoding = "utf-8" ?>
|
02
|
< manifest xmlns:android = "http://schemas.android.com/apk/res/android" android:versionname = "1.0" android:versioncode = "1" package = "android.basic.lesson21" >
|
03
|
< application android:icon = "@drawable/icon" android:label = "@string/app_name" >
|
04
|
< activity android:label = "@string/app_name" android:name = ".MainBroadcastReceiver" >
|
05
|
< intent -filter = "" >
|
06
|
< action android:name = "android.intent.action.MAIN" >
|
07
|
< category android:name = "android.intent.category.LAUNCHER" >
|
08
|
</ category ></ action ></ intent >
|
09
|
</ activity >
|
10
|
<!-- 定义Broadcast Receiver 指定监听的Action -->
|
11
|
< receiver android:name = "HelloBroadReciever" >
|
12
|
< intent -filter = "" >
|
13
|
< action android:name = "android.intent.action.BOOT_COMPLETED" >
|
14
|
</ action ></ intent >
|
15
|
</ receiver >
|
16
|
</ application ></ manifest >
|
4、发布程序,启动模拟器,可以在Logcat中看到:
同时能听到音乐播放的声音。说明我们确实接收到了系统启动的广播事件,并做出了响应。
三、自定义广播
下面我们学习自己制作一个广播。我们接着刚才的例子,继续写下去。
5、在MainBroadcastReceiver.java中填写如下代码:
01
|
package android.basic.lesson21;
|
02
|
03
|
import android.app.Activity;
|
04
|
import android.content.Intent;
|
05
|
import android.os.Bundle;
|
06
|
import android.view.View;
|
07
|
import android.widget.Button;
|
08
|
09
|
public class MainBroadcastReceiver extends Activity {
|
10
|
/** Called when the activity is first created. */
|
11
|
@Override
|
12
|
public void onCreate(Bundle savedInstanceState) {
|
13
|
super .onCreate(savedInstanceState);
|
14
|
setContentView(R.layout.main);
|
15
|
16
|
Button b1 = (Button) findViewById(R.id.Button01);
|
17
|
18
|
b1.setOnClickListener( new View.OnClickListener() {
|
19
|
20
|
@Override
|
21
|
public void onClick(View v) {
|
22
|
//定义一个intent
|
23
|
Intent intent = new Intent().setAction(
|
24
|
"android.basic.lesson21.Hello" ).putExtra( "yaoyao" ,
|
25
|
"yaoyao is 189 days old ,27 weeks -- 2010-08-10" );
|
26
|
//广播出去
|
27
|
sendBroadcast(intent);
|
28
|
}
|
29
|
});
|
30
|
}
|
31
|
}
|
6、更改 HelloBroadReceiver.java 内容如下:
01
|
package android.basic.lesson21;
|
02
|
03
|
import android.content.BroadcastReceiver;
|
04
|
import android.content.Context;
|
05
|
import android.content.Intent;
|
06
|
import android.media.MediaPlayer;
|
07
|
import android.util.Log;
|
08
|
09
|
public class HelloBroadReciever extends BroadcastReceiver {
|
10
|
11
|
//如果接收的事件发生
|
12
|
@Override
|
13
|
public void onReceive(Context context, Intent intent) {
|
14
|
//对比Action决定输出什么信息
|
15
|
if (intent.getAction().equals( "android.intent.action.BOOT_COMPLETED" )){
|
16
|
Log.e( "HelloBroadReciever" , "BOOT_COMPLETED !!!!!!!!!!!!!!!!!!!!!!!!!" );
|
17
|
}
|
18
|
19
|
if (intent.getAction().equals( "android.basic.lesson21.Hello" )){
|
20
|
Log.e( "HelloBroadReciever" , "Say Hello to Yaoyao !!!!!!!!!!!!!!!!!!!!!!!!!" );
|
21
|
Log.e( "HelloBroadReciever" , intent.getStringExtra( "yaoyao" ));
|
22
|
}
|
23
|
24
|
//播放一首音乐
|
25
|
MediaPlayer.create(context, R.raw.babayetu).start();
|
26
|
}
|
27
|
}
|
7、更改 AndroidManifest.xml 内容如下:
01
|
<? xml version = "1.0" encoding = "utf-8" ?>
|
02
|
< manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "android.basic.lesson21" android:versionname = "1.0" android:versioncode = "1" >
|
03
|
< application android:icon = "@drawable/icon" android:label = "@string/app_name" >
|
04
|
< activity android:label = "@string/app_name" android:name = ".MainBroadcastReceiver" >
|
05
|
< intent -filter = "" >
|
06
|
< action android:name = "android.intent.action.MAIN" >
|
07
|
< category android:name = "android.intent.category.LAUNCHER" >
|
08
|
</ category ></ action ></ intent >
|
09
|
</ activity >
|
10
|
<!-- 定义Broadcast Receiver 指定监听的Action 这里我们的接收器,接收了2个Action,一个系统的一个我们自定义的 -->
|
11
|
< receiver android:name = "HelloBroadReciever" >
|
12
|
< intent -filter = "" >
|
13
|
< action android:name = "android.intent.action.BOOT_COMPLETED" >
|
14
|
</ action ></ intent >
|
15
|
< intent -filter = "" >
|
16
|
< action android:name = "android.basic.lesson21.HelloYaoYao" >
|
17
|
</ action ></ intent >
|
18
|
19
|
</ receiver >
|
20
|
</ application >
|
21
|
< uses -sdk = "" android:minsdkversion = "8" >
|
22
|
</ uses ></ manifest >
|
8、运行程序,点击按钮,查看LogCat,听听声音
好了,本讲就到这里。
2
Broadcast Receiver用于接收并处理广播通知(broadcast announcements)。多数的广播是系统发起的,如地域变换、电量不足、来电来信等。程序也可以播放一个广播。程序可以有任意数量的 broadcast receivers来响应它觉得重要的通知。broadcast receiver可以通过多种方式通知用户:启动activity、使用NotificationManager、开启背景灯、振动设备、播放声音等,最 典型的是在状态栏显示一个图标,这样用户就可以点它打开看通知内容。
通常我们的某个应用或系统本身在某些事件(电池电量不足、来电来短信)来临时会广播一个Intent出去,我们可以利用注册一个Broadcast Receiver来监听到这些Intent并获取Intent中的数据。
1. 我们自己的程序主动广播Intent
- final String BROADCAST = "com.forrest.action.mybroadcast";
- Intent intent = new Intent(BROADCAST); // 对应setAction()
- intent.putExtra("data_title", "来短信啦");
- intent.putExtra("data_text", "美女你好,晚上可有空");
- sendBroadcast(intent);
2.接收广播
接收broadcast需要注册一个Broadcast Receiver,并且要注册一个Intent Filter来制定Broadcase Receiver是对哪些Intent进行监听。
(1)注册Broadcast Receiver
一个Broadcast receiver只有一个简单的回调函数:onReceive(Context curContext, Intent broadcastMsg),当一个广播消息被Receiver监听到时,Android会调用它的onReceive()方法,并将包含消息的Intent对象传给它。onReceive中代码的执行时间不要超过5s,否则android会弹出超时dialog。 此时是否另开一个线程来处理耗时的操作呢?
Receiver只在onReceive方法执行时是激活状态,只要onReceive一返回,Receiver就不再是激活状态了。Receiver进程是被一个激活状态的broadcast receiver所保护而不被系统终止的,一旦onReceive返回,Receiver进程broadcast receiver所保护而变为一个空进程,空进程是可以在任意时刻被终止的。这就带来了一个问题:当响应一个广播信息的处理十分耗时的时候,那么就应该把这个处理放在一个单独的线程里去执行,来保证主线程里的其他用户交互组件能够继续运行,而一旦这么做,当onReceive()唤起一个线程后就会马上返回,这时就会把Receiver进程放到被终止的境地。解决这个问题的方案是在onReceive()里开始一个Service,让这个Service去做这件事情,那么系统就会认为这个进程里还有活动正在进行。
(2)注册/注销Broadcast Receiver
1)在AndroidManifest.xml中注册
- <receiver android:name="Receiver1">
- <intent-filter>
- <!-- 和Intent中的action对应 -->
- <action android:name="com.forrest.action.mybroadcast"/>
- </intent-filter>
- </receiver>
2)在代码中注册
- IntentFilter filter = new IntentFilter("com.forrest.action.mybroadcast"); // 和广播中Intent的action对应
- MyBroadcastReceiver br = new MyBroadcastReceiver();
- registerReceiver(new MyBroadcastReceiver(), filter);
3)注销
- unregisterReceiver(br);
3. 示例代码
- public class Receiver1 extends BroadcastReceiver {
- private Context context;
- public static final int NOTIFICATION_ID = 10001;
- public void onReceive(Context context, Intent intent) {
- this.context = context;
- showNotification();
- }
- private void showNotification() {
- Notification notification = new Notification(R.drawable.icon, "来电话啦...", System.currentTimeMillis());
- PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
- notification.setLatestEventInfo(context, "来电话啦...嘿嘿", "赶紧接电话,否则误大事了", contentIntent);
- NotificationManager notificationManager = (NotificationManager) context.getSystemService(
- android.content.Context.NOTIFICATION_SERVICE);
- notificationManager.notify(NOTIFICATION_ID, notification);
- }
- }
- public class Receiver2 extends BroadcastReceiver {
- private Context context;
- @Override
- public void onReceive(Context context, Intent intent) {
- this.context = context;
- deleteNotification();
- }
- private void deleteNotification() {
- NotificationManager notificationManager = (NotificationManager) context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
- notificationManager.cancel(Receiver1.NOTIFICATION_ID);
- }
- }
- public class MainActivity extends Activity {
- private final String ACTION_SEND = "com.forrest.action.SENDMESSAGE",
- ACTION_CLEAR = "com.forrest.action.CLEARNOTIFICATION";
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- ( (Button) findViewById(R.id.btn1) ).setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- clickMenuItem(ACTION_SEND);
- }
- });
- ( (Button) findViewById(R.id.btn2) ).setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- clickMenuItem(ACTION_CLEAR);
- }
- });
- }
- private void clickMenuItem(final String action) {
- Intent intent = new Intent(action);
- sendBroadcast(intent);
- }
- }
注册Broadcast Reciver
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <activity android:name=".MainActivity"
- 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="Receiver1">
- <intent-filter>
- <action android:name="com.forrest.action.SENDMESSAGE"/>
- </intent-filter>
- </receiver>
- <receiver android:name="Receiver2">
- <intent-filter>
- <action android:name="com.forrest.action.CLEARNOTIFICATION"/>
- </intent-filter>
- </receiver>
- </application>
4.
Boardcast receiver相关推荐
- Boardcast Receiver 源码分析:广播的动态注册、发送和接收过程
文章目录 动态注册过程 ContextWrapper#registerReceiver(以下代码基于API26) ContextImpl#registerReceiver ContextImpl#re ...
- AndroidManifest.xml配置详解
2019独角兽企业重金招聘Python工程师标准>>> AndroidManifest.xml配置文件对于Android应用开发来说是非常重要的基础知识,本文旨在总结该配置文件中重点 ...
- AndroidManifest.xml配置文件详解
AndroidManifest.xml配置文件详解 . AndroidManifest.xml配置文件对于Android应用开发来说是非常重要的基础知识,本文旨在总结该配置文件中重点的用法,以便日后查 ...
- Android开发精要2--Android组件模型解析
本文的主要内容如下: 2.1 基于Mashup的应用设计 2.2 界面组件Activity解析 2.3 服务组件Service解析 2.4 触发器组件BroadcastReceiver解析 2.5 数 ...
- AndroidManifest.xml配置文件属性详解
AndroidManifest.xml配置文件对于Android应用开发来说是非常重要的基础知识,本文旨在总结该配置文件中重点的用法,以便日后查阅.下面是一个标准的AndroidManifest.xm ...
- xml 和android脚本之家,AndroidManifest.xml配置文件解析_Android_脚本之家
标签的语法范例. android:alwaysRetainTaskState=['true' | 'false'] android:clearTaskOnLaunch=['true' | 'false ...
- Android面试资料整理
文章目录 前言 面试问题整理 Android 问题 一.Activity 1.Activity 的生命周期 2.onStart()和onResume().onPause()和onStop()的区别? ...
- Handler完全解读——Handler的使用
个人博客:https://blog.N0tExpectErr0r.cn 小专栏:https://xiaozhuanlan.com/N0tExpectErr0r Handler完全解读--Handler ...
- Spark Streaming笔记整理(二):案例、SSC、数据源与自定义Receiver
[TOC] 实时WordCount案例 主要是监听网络端口中的数据,并实时进行wc的计算. Java版 测试代码如下: package cn.xpleaf.bigdata.spark.java.str ...
最新文章
- Constraint4:default约束
- Spring 整合Struts2
- c++ STL find search
- 2字节取值范围_高中数学:构造不等式,解析几何范围题的有效解法
- 领导要提拔你的5个征兆,机会来临时不要让自己错过
- 3d object是什么文件_[单目3D目标检测论文笔记] 3D Bounding Box Estimation
- dialog问题记录
- PostgreSQL 为什么不要滥用unlogged table hash index
- 计算机网络网线颜色,网络线接法-各种网线的分类和区别-电气资讯 - 电工屋
- 从一个编程老菜鸟来看Delphi的优点
- 一个页面中有两个iframe
- SDN相关组织——ODL
- Python爬取URP教务系统课程表并保存到excel
- 【沐风老师】教你在3dMax中使用Greeble插件结合变形修改器建模
- android 各国时区
- 【Java】使用lambda表达式获取list中所有对象的某个属性以及获取特定属性的某一个对象
- 电脑重装了系统开不了机怎么办?
- 发一个贷款月供额计算工具[原创]
- Skimming, Locating, then Perusing: A Human-Like Framework for Natural Language Video Localization
- 【例4-3】利用数组,给定N个正整数数据(N<=100),查找最大值和最小值并输出。【输入输出样例】Input length (N<=100):(此处括号、冒号为英文符号,后面无空格;leng
热门文章
- DSP的时钟和系统控制
- github上比较好用的第三方
- [IMX6Q][Android4.4] Audio添加控制MIC左右声道接口
- 2020-2021中国区块链企业发展白皮书.pdf.
- AS 导出aar给Unity出打包出现Unable to merge android manifests
- Alarmmanager制作简单闹钟功能
- 常用Unity平台解释
- android之GMS认证
- php session传数组,php session存储数组
- Spring——Spring两大特性:IOC+AOP