四大组件之BroadcastReceiver基础
1. 系统广播
1.1 动态注册
(1)创建自定义接收器类继承自BroadcaseReceiver,实现onReceive()方法,对接收到的广播的逻辑处理就是写在这个函数中的。
(2)实例化IntentFilter对象,并通过addAction()方法加入需要接收的广播值。使用系统广播时可查阅官方文档,找到需要的Action。
(3)实例化自定义接收器类的对象,并通过registerReceiver()方法注册接收器对象。
(4)在AndroidManifest.xml文件中,通过uses=permission标签进行权限声明。若非系统的关键性信息,则无需这一步。
(5)使用完后,动态注册的广播接收器一定要通过unregisterReceiver()方法取消注册。
范例: 监测当前网络状态,若断网,则提示用户当前网络不可用。
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.studying.myapplication">
<!--声明权限-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".BroadcaseActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
活动类:
public class BroadcaseActivity extends Activity {
private IntentFilter mFilter;
private NetworkChangeReceiver mReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broadcase);
//实例化IntentFilter对象,并加入Action
mFilter = new IntentFilter();
mFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
mReceiver = new NetworkChangeReceiver();
//注册接收器
registerReceiver(mReceiver, mFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
//动态注册的广播接收器一定要取消注册
unregisterReceiver(mReceiver);
}
class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//获取网络状态信息
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
//当网络信息对象为空或者网络不可用时,提示用户
if (networkInfo == null || !networkInfo.isAvailable()) {
Toast.makeText(context, "Network is unavailable.", Toast.LENGTH_SHORT).show();
}
}
}
}
1.2 静态注册
相对动态注册而言,静态注册接收器非常简单,只需要自定义一个接收器类,而后实现onReceive()方法,在里面实现对广播的处理,然后在AndroidManifest.xml文件中通过receiver标签进行注册即可。需要注意,无论是静态注册还是动态注册,如果需要访问系统的关键性信息,都必须在配置文件中声明权限。
范例: 静态注册实现开机自启。
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.studying.myapplication">
<!--声明权限-->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!--通过receiver标签静态注册-->
<receiver android:name=".BootCompleteReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity android:name=".BroadcaseActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
自定义接收器类:
public class BootCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Boot Complete..", Toast.LENGTH_SHORT).show();
}
}
2. 自定义广播
2.1 标准广播
自定义广播的接收方法与系统广播的一样,也有静态注册和动态注册两种方法,这里就不再赘述。
自定义广播的不同之处在于,它是手动发送的,方法是新建一个Intent对象并加入自定义的广播值,而后通过sendBroadcase()方法发送,此时发送出去的就是一条标准广播。
范例: 发送一条自定义标准广播并接收。
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.studying.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!--通过receiver标签静态注册-->
<receiver android:name=".MyReceiver" >
<intent-filter>
<action android:name="com.studying.MyBroadcast" />
</intent-filter>
</receiver>
<activity android:name=".BroadcaseActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
自定义接收器类:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Received.", Toast.LENGTH_SHORT).show();
}
}
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.studying.myapplication.BroadcaseActivity">
<Button
android:id="@+id/send"
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="Send MyBroadcase" />
</LinearLayout>
活动类:
public class BroadcaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broadcase);
Button send = (Button) findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//实例化一个Intent对象,并发送广播
Intent intent = new Intent("com.studying.MyBroadcast");
sendBroadcast(intent);
}
});
}
}
2.2 有序广播
与标准广播不同之处在于,标准广播是异步执行的,所有广播接收器会在同一时刻接收到;而有序广播是同步执行的,同一时刻只会有一个接收器收到,当这个接收器里面的逻辑执行完毕后,广播才会继续传播。
因此,有序广播有两个要点,第一,优先级高的接收器可以先收到广播,优先级高低通过priority给定;第二,前面的接收器可以截断,让后面的接收器无法收到广播,这个则是通过abortBroadcase()方法实现。
此外,有序广播是通过sendOrderedBroadcase()方法进行发送的。
范例: 创建两个自定义广播类,并且让MyReceiver1的优先级高于MyReceiver2,而后在MyReceiver1中调用abortBroadcase()方法截断广播的传递。
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.studying.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!--使MyReceiver1的优先级高于MyReceiver2的-->
<receiver android:name=".MyReceiver1" >
<intent-filter android:priority="100">
<action android:name="com.studying.MyBroadcast" />
</intent-filter>
</receiver>
<receiver android:name=".MyReceiver2" >
<intent-filter android:priority="50">
<action android:name="com.studying.MyBroadcast" />
</intent-filter>
</receiver>
<activity android:name=".BroadcaseActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
布局文件与标准广播的范例一样:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.studying.myapplication.BroadcaseActivity">
<Button
android:id="@+id/send"
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="Send MyBroadcase" />
</LinearLayout>
活动类:
public class BroadcaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broadcase);
Button send = (Button) findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//发送有序广播
Intent intent = new Intent("com.studying.MyBroadcast");
sendOrderedBroadcast(intent, null);
}
});
}
}
MyReceiver1:
public class MyReceiver1 extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Received in MyReceiver1.", Toast.LENGTH_SHORT).show();
abortBroadcast();
}
}
MyReceiver2:
public class MyReceiver2 extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Received in MyReceiver2.", Toast.LENGTH_SHORT).show();
}
}
若把MyReceiver1中的abortBroadcase();这一句注释掉,点击发送则可一次看到两个接收器的提示。
3. 本地广播
本地广播只能够在应用程序内部进行传递,广播接收器也只能接收本程序发出的广播,这样的机制解决了全局广播可能出现的安全问题。
使用本地广播非常简单,与全局广播不一样的地方在于,使用了一个LocalBroadcastManager对广播进行管理,使用这个管理器发送的广播以及注册的接收器,即为本地广播和本地广播接收器。
另外,由于发送本地广播时,程序必定处于启动状态,因而不需要并且也没有静态注册。
范例: 发送一条本地广播并接收。
活动类:
public class BroadcaseActivity extends Activity {
private MyReceiver mReceiver;
private LocalBroadcastManager mManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broadcase);
//获取本地广播管理器
mManager = LocalBroadcastManager.getInstance(this);
Button send = (Button) findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//通过本地广播管理器发送广播
Intent intent = new Intent("com.studying.MyLocalBroadcast");
mManager.sendBroadcast(intent);
}
});
//通过本地广播管理器进行动态注册
IntentFilter mFilter = new IntentFilter();
mFilter.addAction("com.studying.MyLocalBroadcast");
mReceiver = new MyReceiver();
mManager.registerReceiver(mReceiver, mFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
//通过本地广播管理器取消注册
mManager.unregisterReceiver(mReceiver);
}
//自定义接收器类
class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Received.", Toast.LENGTH_SHORT).show();
}
}
}
最后,在使用广播接收器时要注意,不要在onReceive()方法中加任何耗时操作,广播接收器更多的是接收某些广播讯息,从而开启其它组件。在广播接收器中是不允许开启线程的,当onReceive()方法运行了长时间仍未结束时,程序就会报错。
四大组件之BroadcastReceiver基础的更多相关文章
- [置顶] Android四大组件之BroadcastReceiver
Android四大组件之BroadcastReceiver Broadcast Receiver 广播接收器,是一种负责接收广播消息并对消息做出响应的组件,和Service一样并不提供与用户交互的UI ...
- Android实训案例(六)——四大组件之一BroadcastReceiver的基本使用,拨号,短信,SD卡,开机,应用安装卸载监听
Android实训案例(六)--四大组件之一BroadcastReceiver的基本使用,拨号,短信,SD卡,开机,应用安装卸载监听 Android中四大组件的使用时重中之重,我这个阶段也不奢望能把他 ...
- Android 四大组件之“ BroadcastReceiver ”
前言 Android四大组件重要性已经不言而喻了,今天谈谈的是Android中的广播机制.在我们上学的时候,每个班级的教室里都会装有一个喇叭,这些喇叭都是接入到学校的广播室的,一旦有什么重要的通知,就 ...
- Android四大组件:BroadcastReceiver 介绍
介绍 BroadcastReceiver 即广播组件,是 Android 的四大组件之一.用于监听和接收广播消息,并做出响应.有以下一些应用: 不同组件之间的通信(应用内或不同应用之间). 多线程之间 ...
- Android四大组件简介:Android 基础知识,开发教程
Android 四大组件: Activity.Service.Broadcast Receiver.Content Provider. http://developer.android.com/int ...
- 四大组件之BroadcastReceiver
BroadcastReceiver,顾名思义就是“广播接收者”的意思,它是Android四大基本组件之一,这种组件本质上是一种全局的监听器,用于监听系统全局的广播消息.它可以接收来自系统和应用的的广播 ...
- Android四大组件之BroadcastReceiver
什么是BroadcastReceiver? BroadcastReceiver也就是“广播接收者”的意思,顾名思义,它就是用来接收来自系统和应用中的广播. 在Android系统中,广播体现在方方面面, ...
- Android 四大组件之 BroadcastReceiver
0 简介 BroadcastReceiver也就是“广播接收者”的意思,顾名思义,它就是用来接收来自系统和应用中的 广播. 在Android系统中,广播体现在方方面面,例 ...
- Android_四大组件之BroadcastReceiver
一.概述 BroadcastReceiver是广播接收器,接收来自 系统或应用发出的广播信息 并进行相应的逻辑处理. 自定义BroadcastReceiver只需继承android.content.B ...
随机推荐
- Base64算法原理
3个Byte (3 X 8 = 24 bits) 以3个字节为单位,依次取6位数据,并在前面补上2个0.这样就增加了一个字节的数据.
- 【基础】26个命令玩转linux,菜鸟及面试必备
1 查看目录与文件:ls #显示当前目录下所有文件的详细信息 ls -la 2 切换目录:cd #切换当前目录为/opt/test cd /opt/test 3 显示当前目录:pwd pwd 4 创建 ...
- abp中文件下载,将内存数据导出到Excel并下载
1.数据导出为Excel的Stream using System; using System.Collections.Generic; using System.IO; using Abp.Colle ...
- ADO.NET通用类库
using System.Data; using System.Data.SqlClient; namespace DataService { public class SQLHelper { pub ...
- Mybatis学习之道(一)
本例子为采用的mysql+maven+mybatis构建. 初步学习mybatis: mybatis为一个半自动框架,相对于hibernate来说他更加轻巧,学习成本更低. 1.新建一个maven工程 ...
- mac中配置jdk环境
- 使用Netbeans内置的Git工具
在 NetBeans IDE 中使用 Git 支持 NetBeans IDE 为 Git 版本控制客户端提供支持.通过利用 IDE 的 Git 支持,您可以从 IDE 内的项目中直接执行版本控制任务. ...
- win10外接键盘失灵
故障描述:笔记本外接的键盘突然之间就失灵,键盘的灯不亮,无法输入 处理方程: 1. 我的电脑右击--> 管理 --> 设备管理器(开始失灵时,键盘下的HID Keyboard Device ...
- POJ - 1456 贪心+并查集
做法一:直接贪心,按照利润排序,然后直接尽量给每个活动安排到最晚的时间即可.时间复杂度O(n * d)当d都为10000时,很容易超时.由于这题数据比较水,所有贪心未超时. AC代码 #include ...
- APICloud ajpush(极光推送) 6009
APICloud 其它的都按照APICloud的使用说明操作即可,但有一点需要提醒像我一样才接触的朋友:极光推送需打包测试,不能直接自定义Loader.否则,你会发现在绑定别名的方法时会一直返回&qu ...