前言:

最近的计划是学习一下iOS的NSNotificationCenter,突然想起来的Android的广播机制,所以还是觉得先对BroadcastReceiver来个全面的总结然后再去学习NSNotificationCenter。

BroadcastReceiver简介:

BroadcastReceiver是Android四大组件之一,广播是一种广泛运用的在应用程序之间传输信息的机制,而BroadcastReceiver 是对发送出来的广播进行过滤接收并响应的一类组件;广播接收者( BroadcastReceiver )用于接收广播 Intent ,广播 Intent 的发送是通过调用 Context.sendBroadcast() 、 Context.sendOrderedBroadcast() 来实现的。通常一个广播 Intent 可以被订阅了此 Intent 的多个广播接收者所接收。

广播的使用场景:

1.同一app内部的同一组件内的消息通信(单个或多个线程之间);

2.同一app内部的不同组件之间的消息通信(单个进程);

3.同一app具有多个进程的不同组件之间的消息通信;

4.不同app之间的组件之间消息通信;

5.Android系统在特定情况下与App之间的消息通信。

广播的分类:

      普通广播:

发送方式:Context.sendBroadcast()

优点:完全异步,消息传递效率高,

缺点:不能处理广播传给一个接收者,不能终止广播的传播

      有序广播:

发送方式:Context.sendOrderedBroadcast()

优点:可以根据广播接收者的优先级依次传播,广播接收者可以处理广播然后再传给一下广播接收者,也可以根据需要调用abortBroadcast()终止广播传播。

缺点:效率低

广播的使用方式:

动态注册:

  //注册广播
private void registerReceiver(){
IntentFilter dynamicFilter = new IntentFilter();
dynamicFilter.addAction(ActionCodes.DYNAMICACTION);//添加动态广博Action
registerReceiver(dynamicReceiver, dynamicFilter);
} //解除注册
private void unRegisterReceiver()
{
unregisterReceiver(dynamicReceiver);
} //动态广播的Receiver
private BroadcastReceiver dynamicReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(ActionCodes.DYNAMICACTION)){ //动作检测
String msg = intent.getStringExtra("msg");
String finalMsg= String.format("%s%s","CActivity----->收到广播:",msg);
Log.e("dynamicReceiver",finalMsg);
Toast.makeText(context, finalMsg, Toast.LENGTH_SHORT).show();
}
}
};

一般情况在Activity/Fragment 的onCreate/onStart/onResume 中注册, 在onDestory/onStop/onPause 中解除注册,根据不同的需求选择不能的生命周期函数。

静态注册:

       <receiver
android:name=".StaticReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="100">
<action android:name="com.whoislcj.broadcastreceiver.staticreceiver" />
</intent-filter>
</receiver>

发送广播:

                //发送普通广播
Intent intent = new Intent();
intent.setAction(ActionCodes.DYNAMICACTION);//设置Action
intent.putExtra("msg", "我是普通广播(动态注册)");//添加附加信息
sendBroadcast(intent); //发送有序广播
Intent intent = new Intent();
intent.setAction(ActionCodes.DYNAMICACTION);//设置Action
intent.setPackage(getPackageName());//设置包名
intent.putExtra("msg", "我是有序广播(动态注册)");//添加附加信息
sendOrderedBroadcast(intent,null);

以上基本上可以满足广播的基本使用了,接下来我们在写个测试程序:分别在A,B,C三个Activity中动态注册广播,分别发送普通广播和和有序广播。

发送普通广播接收顺序:

分别给A,B,C三个Activity中动态注册广播的优先级设置未100,500,1000接收顺序:

附上设置优先级方式:

        IntentFilter dynamicFilter = new IntentFilter();
dynamicFilter.addAction(ActionCodes.DYNAMICACTION);//添加动态广播的Action
dynamicFilter.setPriority(1000);//设置优先级
registerReceiver(dynamicReceiver, dynamicFilter);

上文已知有序广播可以修改广播信息传递给下一级优先级低的接收者,我们让BActivity修改 让AActivity接收:

BActivity 广播实现

 //动态广播的Receiver
private BroadcastReceiver dynamicReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(ActionCodes.DYNAMICACTION)){ //动作检测
String msg = intent.getStringExtra("msg");
String finalMsg= String.format("%s%s","BActivity----->收到广播:",msg);
Log.e("dynamicReceiver",finalMsg);
Toast.makeText(context, finalMsg, Toast.LENGTH_SHORT).show(); if(isOrderedBroadcast()) {
//创建一个Bundle对象,并存入数据
Bundle bundle = new Bundle();
bundle.putString("msg", msg + "来自BActivity");
//将bundle放入结果中
setResultExtras(bundle);
//取消Broadcast的继续发送
//abortBroadcast();
}
}
}
};

AActivity 如何接收:

   //动态广播的Receiver
private BroadcastReceiver dynamicReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(ActionCodes.DYNAMICACTION)) { //动作检测 String msg = intent.getStringExtra("msg");
String finalMsg = String.format("%s%s", "AActivity----->收到广播:", msg);
Log.e("dynamicReceiver", finalMsg);
if (isOrderedBroadcast()) {
Bundle bundle = getResultExtras(true);//接收来自上一级优先级较高的广播修改的信息
String from = bundle.getString("msg");
if (TextUtils.isEmpty(from)) {
return;
}
Log.e("dynamicReceiver", String.format("%s%s", "AActivity----->收到广播:", from));
Toast.makeText(context, finalMsg, Toast.LENGTH_SHORT).show();
}
}
}
};

运行结果:

有序广播如何终止广播传播:

                 // 终止Broadcast的继续发送
abortBroadcast();

运行结果:

静态注册的广播上述测试运行结果一致,设置优先级方式不同而已:

        <receiver
android:name=".AStaticReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="100"><!--设置优先级-->
<action android:name="com.whoislcj.broadcastreceiver.staticreceiver" />
</intent-filter>
</receiver>

接下来测试一下app应用之间发送广播,发送方式也是通过隐式Intent方式:

动态注册广播接收情况:

普通广播:

有序广播:

静态注册广播接收情况:

普通广播:

有序广播:

看了上述测试结果基本上和app内运行效果一模一样,所以按照上述那种注册方式和使用方式,一旦app被反编译之后有一定的安全隐患,如何安全的传输呢?

第一种方式:

静态注册广播可以设置:android:exported="false"

          <receiver
android:name=".AStaticReceiver"
android:enabled="true"
android:exported="false" <!--设置只能接收app内广播 -->
>
<intent-filter android:priority="100"><!--设置优先级-->
<action android:name="com.whoislcj.broadcastreceiver.staticreceiver" />
</intent-filter>
</receiver>

第二种方式:通过设置发送的广播只能app内接收

                Intent intent = new Intent();
intent.setAction(ActionCodes.DYNAMICACTION);//设置Action
intent.setPackage(getPackageName());//设置包名使广播只能被包名的app内接收者接收
intent.putExtra("msg", "我是普通广播(动态注册)");//添加附加信息
sendBroadcast(intent);

第三种方式通过自定义权限:通过上述两种方式只能达到屏蔽外来广播以及广播只在app内传播,无法实现app之间安全发送广播

自定义权限:

    <permission android:name="com.whoislcj.broadcastreceiver.MySelfBroadcastReceiver" />

    <uses-permission android:name="com.whoislcj.broadcastreceiver.MySelfBroadcastReceiver"/>

动态注册:

        IntentFilter dynamicFilter = new IntentFilter();
dynamicFilter.addAction(ActionCodes.DYNAMICACTION);//添加动态广播的Action
dynamicFilter.setPriority(500);
//设置权限
registerReceiver(dynamicReceiver, dynamicFilter,ActionCodes.MYPERMISSION,null);

静态注册:

         <receiver
android:name=".BStaticReceiver"
android:enabled="true"
android:exported="true"
<!--设置权限-->
android:permission="com.whoislcj.broadcastreceiver.MySelfBroadcastReceiver">
<intent-filter android:priority="500">
<action android:name="com.whoislcj.broadcastreceiver.staticreceiver" />
</intent-filter>
</receiver>

发送广播:

                //普通广播
sendBroadcast(intent,ActionCodes.MYPERMISSION); //有序广播
sendOrderedBroadcast(intent,ActionCodes.MYPERMISSION);

第四种方式:通过LocalBroadcastManager方式

注册:

LocalBroadcastManager.getInstance(getInstance()).registerReceiver(receiver, filter);

解除注册:

LocalBroadcastManager.getInstance(getInstance()).unregisterReceiver(receiver);

发送广播:

LocalBroadcastManager.getInstance(getInstance()).sendBroadcastSync(intent);

总结:

通过本文可以看出BroadcastReceiver使用方式虽然看似简单,想要实现比较完善的广播还是要费一番功夫的。

Android探索之BroadcastReceiver具体使用以及安全性探究的更多相关文章

  1. Android View各种尺寸位置相关的方法探究

    Android View各种尺寸位置相关的方法探究 本来想做一个View间的碰撞检测之类的. 动手做了才发现不是想象的那么简单. 首先,写好了碰撞检测的工具类如下: package com.mengd ...

  2. Android LocalBroadcastManager 与 BroadcastReceiver

    Android中BroadcastReceiver主要用途有 发送通知,更新UI或者数据,应用程序间相互通信,监听系统状态(比如开机,网络等) Android中发送广播的方式: 普通广播:无论优先级大 ...

  3. Android探索之旅 | AIDL原理和实例讲解

    轉載自http://www.jianshu.com/p/ef86f682a8f9 -- 作者 谢恩铭 转载请注明出处 前言 为使应用程序之间能够彼此通信,Android提供了IPC (Inter Pr ...

  4. Android探索之AIDL实现进程间通信

    前言: 前面总结了程序间共享数据,可以使用ContentProvider也可以使用SharedPreference,那么进程间怎么共享内存呢?Android系统中的进程之间不能共享内存,因此,需要提供 ...

  5. Android - 广播接收者 - BroadcastReceiver

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

  6. android广播接收器BroadcastReceiver

    首先看一下什么是 BroadcastReceiver BroadcastReceiver:直译是"广播接收者",所以它的作用是用来接收发送过来的广播的. 那我们有必要知道:什么是广 ...

  7. Android 学习笔记 BroadcastReceiver广播...

    PS:不断提升自己,是件好事... 学习内容: 1.BroadcastReceiver的使用.. 2.通过BroadcastReceiver去启动Service... 1.BroadcastRecei ...

  8. Android 利用Service BroadcastReceiver实现小例子

    Activity: package com.example.test; import android.app.Activity; import android.content.Context; imp ...

  9. Android开发之BroadcastReceiver

    BroadcastReceiver:广播接收者.用来接收系统或应用中的广播. 在Android系统中,广播体现在方方面面,例如当开机完成后系统会产生一条广播,接收到这条广播就能实现开机启动服务的功能: ...

随机推荐

  1. NOI 题库 9272 题解

    9272   偶数个数字3 描述 在所有的N位数中,有多少个数中有偶数个数字3? 输入 一行给出数字N,N<=1000 输出 如题 样例输入 2 样例输出 73 Solution : 令f ( ...

  2. JavaScript-Object基础知识

    1.   定义:对象是JS的核心概念,也是最重要的数据类型.js的所有数据都可以被视为对象.                 对象是一种无序的数据集合,由若干个键值对(key:value)构成,由{ ...

  3. sublime 安装 插件

    从菜单 View - Show Console 或者 ctrl + ~ 快捷键,调出 console.将以下 Python 代码粘贴进去并 enter 执行,不出意外即完成安装.以下提供 ST3 和 ...

  4. webScoket的浅短的认识

    在一般的发送数据请求的时候都是用的http协议,但是对于类似即时聊天,需要客户端与服务器不间断的交互的时候对于http协议来说就不太适用了.因为http协议无法主动把数据发到客户端,而且客户端发送请求 ...

  5. 《JavaScript Dom编程艺术》(第二版)

    第一章<JavaScript简史> 1.JavaScript是一种脚本语言,通常只能通过Web浏览器去完成一些操作而不能像普通意义上的程序那样独立运行,它需要由Web浏览器进行解释和执行. ...

  6. css技巧

    1.实现position为fixed与absolute值时居中定位: 给需要定位的元素块外加一层div盒子,外层div盒子存在于文档流中,让外层div盒子居中定位并设置position属性为relat ...

  7. nginx-(/etc/init.d/nginx)启动脚本

    #!/bin/bash #nx Startup script for the Nginx HTTP Server # it is v. version. # chkconfig: - # descri ...

  8. OS中atomic的实现解析

    OS中atomic的实现解析 转自:http://my.oschina.net/majiage/blog/267409    摘要 atomic属性线程安全,会增加一定开销,但有些时候必须自定义ato ...

  9. C++ 控制台代码输出控制

    在C++控制台应用程序中可以控制控制台输出的字体颜色和 接受任意按键退出 #ifndef CONSOLE_UTILS_H #define CONSOLE_UTILS_H #include <wi ...

  10. 开源消息队列:NetMQ

    NetMQ 是  ZeroMQ的C#移植版本. ZeroMQ是一个轻量级的消息内核,它是对标准socket接口的扩展.它提供了一种异步消息队列,多消息模式,消息过滤(订阅),对多种传输协议的无缝访问. ...