android初学者_适用于初学者的Android广播接收器

android初学者

Let’s say you have an application that depends on a steady internet connection. You want your application to get notified when the internet connection changes. How do you do that?

假设您有一个依赖稳定互联网连接的应用程序。 您希望您的应用程序在Internet连接更改时得到通知。 你是怎样做的?

A possible solution would be a service which always checks the internet connection. This implementation is bad for various reasons so we won’t even consider it. The solution to this problem is a Broadcast Receiver and it will listen in on changes you tell it to.

一种可能的解决方案是始终检查互联网连接的服务。 由于各种原因,此实现都是不好的,因此我们甚至不会考虑。 解决此问题的方法是广播接收器,它将侦听您告诉它的更改。

A broadcast receiver will always get notified of a broadcast, regardless of the status of your application. It doesn’t matter if your application is currently running, in the background or not running at all.

无论您的应用程序处于什么状态,广播接收器始终会收到广播通知。 您的应用程序当前正在运行,在后台运行还是根本不运行都没有关系。

背景 (Background)

Broadcast receivers are components in your Android application that listen in on broadcast messages(or events) from different outlets:

广播接收器是Android应用程序中的组件,用于侦听来自不同出口的广播消息(或事件):

  • From other applications

    从其他应用程序
  • From the system itself

    从系统本身
  • From your application

    从您的应用程序

Meaning, that they are invoked when a certain action has occurred that they have been programmed to listen to (I.E., a broadcast).

意思是,当它们已经被编程为监听(IE,广播)的某个特定动作发生时,将调用它们。

A broadcast is simply a message wrapped inside of an Intent object. A broadcast can either be implicit or explicit.

广播只是包装在Intent对象内部的一条消息。 广播可以是隐式的也可以是显式的。

  • An implicit broadcast is one that does not target your application specifically so it is not exclusive to your application. To register for one, you need to use an IntentFilter and declare it in your manifest. You need to do all of this because the Android operating system goes over all the declared intent filters in your manifest and sees if there is a match. Because of this behavior, implicit broadcasts do not have a target attribute. An example for an implicit broadcast would be an action of an incoming SMS message.

    隐式广播是一种不专门针对您的应用程序的广播 ,因此它不是您的应用程序所独有的。 要注册一个,您需要使用IntentFilter并在清单中声明它。 您需要执行所有这些操作,因为Android操作系统会遍历清单中所有声明的意图过滤器,并查看是否存在匹配项。 由于此行为,隐式广播没有目标属性。 隐式广播的示例是传入SMS消息的操作。

  • An explicit broadcast is one that is targeted specifically for your application on a component that is known in advance. This happens due to the target attribute that contains the application’s package name or a component class name.

    显式广播是专门针对您的应用程序的事先已知组件上的广播 。 发生这种情况是由于目标属性包含应用程序的程序包名称或组件类名称。

There are two ways to declare a receiver:

有两种声明接收方的方法:

  1. By declaring one in your AndroidManifest.xml file with the <receiver> tag (also called static)

    通过在AndroidManifest.xml文件中使用<receiver>标记声明一个(也称为静态)

You will notice that the broadcast receiver declared above has a property of exported=”true”. This attribute tells the receiver that it can receive broadcasts from outside the scope of the application.

您将注意到,上面声明的广播接收器具有export =” true”的属性。 此属性告诉接收者它可以从应用程序范围之外接收广播。

2. Or dynamically by registering an instance with registerReceiver (what is known as context registered)

2.或通过向registerReceiver注册实例来动态地进行(这称为上下文注册)

如何在Android中实现广播接收器 (How to Implement a Broadcast Receiver in Android)

To create your own broadcast receiver, you must first extend the BroadcastReceiver parent class and override the mandatory method, onReceive:

要创建自己的广播接收器,必须首先扩展BroadcastReceiver父类并重写强制方法onReceive:

public void onReceive(Context context, Intent intent) {//Implement your logic here}

Putting it all together yields:

将所有内容放在一起可得出:

public class MyBroadcastReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {StringBuilder sb = new StringBuilder();sb.append("Action: " + intent.getAction() + "\n");sb.append("URI: " + intent.toUri(Intent.URI_INTENT_SCHEME).toString() + "\n");String log = sb.toString();Toast.makeText(context, log, Toast.LENGTH_LONG).show();}
}

⚠️ The onReceive method runs on the main thread, and because of this, its execution should be brief.

The️onReceive方法在主线程上运行,因此,它的执行应该简短。

If a long process is executed, the system may kill the process after the method returns. To circumvent this, consider using goAsync or scheduling a job. You can read more about scheduling a job at the bottom of this article.

如果执行了较长的过程,则该方法返回后,系统可能会终止该过程。 为了避免这种情况,请考虑使用goAsync或安排作业。 您可以在本文底部阅读有关计划作业的更多信息。

动态注册示例 (Dynamic Registration Example)

To register a receiver with a context, you first need to instantiate an instance of your broadcast receiver:

要向上下文注册接收者,首先需要实例化广播接收者的实例:

BroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();

Then, you can register it depending on the specific context you wish:

然后,您可以根据所需的特定上下文进行注册:

IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
this.registerReceiver(myBroadcastReceiver, filter);

Don’t forget to unregister your broadcast receiver when you no longer need it:

当您不再需要广播接收器时,请不要忘记注销它:

@Override
protected void onStop() {super.onStop();unregisterReceiver(myBroadcastReceiver);
}

如何在Android中广播事件 (How to Broadcasting An Event in Android)

The point behind broadcasting messages from your application is to allow your application to respond to events as they happen inside of it.

广播来自应用程序的消息的目的是使您的应用程序能够响应事件在其中发生的情况。

Think of a scenario where in one part of the code, the user performs a certain action and because of it, you want to execute some other logic you have in a different place.

考虑一种场景,在这种情况下,用户在代码的一部分中执行了某个特定的动作,因此,您希望执行其他位置的其他逻辑。

There are three ways to send broadcasts:

有三种发送广播的方法:

  1. The sendOrderedBroadcast method, makes sure to send broadcasts to only one receiver at a time. Each broadcast can in turn, pass along data to the one following it, or to stop the propagation of the broadcast to the receivers that follow

    sendOrderedBroadcast 方法,请确保一次仅将广播发送到一个接收机。 每个广播可以依次将数据传递到其后的广播,或停止将广播传播到随后的接收器

  2. The sendBroadcast is similar to the method mentioned above, with one difference. All broadcast receivers receive the message and do not depend on one another

    sendBroadcast与上述方法类似,但有一个区别。 所有广播接收器都接收到该消息,并且彼此不依赖

  3. The LocalBroadcastManager.sendBroadcast method only sends broadcasts to receivers defined inside your application and does not exceed the scope of your application.

    LocalBroadcastManager.sendBroadcast方法仅将广播发送到应用程序内部定义的接收方,并且不会超出应用程序的范围。

陷阱和注意事项 (Gotchas And Things To Pay Attention To)

  • Do not send sensitive data through an implicit broadcast, because any application listening in for it, will receive it. You can prevent this by either specifying a package or attaching a permission to the broadcast

    不要通过隐式广播发送敏感数据,因为任何监听它的应用程序都将接收它。 您可以通过指定软件包或为广播添加权限来防止这种情况
  • Don’t start activities from a broadcast received as the user experience is lacking. Choose to display a notification instead.

    由于缺少用户体验,因此请勿从收到的广播中开始活动。 选择改为显示通知。

The following bullet points refer to changes in broadcast receivers relevant for each Android OS version (starting from 7.0). For each version, certain limitations have taken places and behavior has changed as well. Keep these limitations in mind when thinking about using a broadcast receiver.

下列要点涉及与每个Android OS版本(从7.0开始)相关的广播接收器中的更改。 对于每个版本,都有一些局限性,行为也发生了变化。 在考虑使用广播接收器时,请牢记这些限制。

  • 7.0 and Up (API level 24) - Two system broadcasts have been disabled, Action_New_Picture and Action_New_Video (but they were brought back in Android O for registered receivers)

    7.0及更高版本(API级别24) -禁用了两个系统广播,即Action_New_Picture和Action_New_Video (但已将它们带回Android O中供注册接收者使用)

  • 8.0 and Up (API level 26) - Most implicit broadcasts need to be registered to dynamically and not statically (in your manifest). You can find the broadcasts that were whitelisted in this link.

    8.0及更高版本(API级别26) -大多数隐式广播需要注册为动态注册,而不是静态注册(在清单中)。 您可以在此链接中找到列入白名单的广播。

  • 9.0 and Up (API level 28) - Less information received on Wi-Fi system broadcast and Network_State_Changed_Action.

    9.0及更高版本(API级别28) -在Wi-Fi系统广播和Network_State_Changed_Action上收到的信息较少。

The changes in Android O are the ones you need to be the most aware of. The reason these changes were made was because it lead to performance issues, battery depletion and hurt user experience. This happened because many applications (even those not currently running) were listening in on a system wide change and when that change happened, chaos ensued. Imagine that every application registered to the action, came to life to check if it needed to do something because of the broadcast. Take into account something like the Wi-Fi state, which changes frequently, and you will begin to understand why these changes took place.

您需要最了解Android O中的更改。 进行这些更改的原因是因为它导致性能问题,电池电量耗尽并损害用户体验。 发生这种情况是因为许多应用程序(甚至是当前未运行的应用程序)正在侦听系统范围的更改,并且当更改发生时,随之而来的是混乱。 想象一下,注册到该动作的每个应用程序都变得生动起来,检查它是否需要因为广播而需要执行某些操作。 考虑到诸如Wi-Fi状态之类的事物,它会经常变化,因此您将开始理解为什么发生这些变化。

广播接收器的替代方案 (Alternatives to Broadcast Receivers)

To make it easier to navigate all these restrictions, below is a breakdown of other components you can use in the absence of a broadcast receiver. Each one has a different responsibility and use case, so try to map out which one caters to your needs.

为了更轻松地浏览所有这些限制,以下是在没有广播接收器的情况下可以使用的其他组件的分解。 每个人都有不同的责任和用例,因此请尝试确定哪个人可以满足您的需求。

  • LocalBroadcastManager - As I mentioned above, this is valid only for broadcasts within your application

    LocalBroadcastManager-如上所述,这仅对您的应用程序中的广播有效

  • Scheduling A Job - A job can be run depending on a signal or trigger received, so you may find that the broadcast you were listening on can be replaced by a job. Furthermore, the JobScheduler, will guarantee your job will finish, but it will take into account various system factors(time and conditions)to determine when it should run. When creating a job, you will override a method called onStartJob. This method runs on the main thread, so make sure that it finishes its work in a limited amount of time. If you need to perform complex logic, consider starting a background task. Furthermore, the return value for this method is a boolean, where true denotes that certain actions are still being performed, and false means the job is done

    计划作业 -可以根据收到的信号或触发器来运行作业,因此您可能会发现您正在收听的广播可以替换为作业。 此外, JobScheduler可以确保您的工作完成,但是它将考虑各种系统因素(时间和条件)来确定何时应运行。 创建作业时,您将覆盖一个名为onStartJob的方法。 此方法在主线程上运行,因此请确保它在有限的时间内完成工作。 如果需要执行复杂的逻辑,请考虑启动后台任务。 此外,此方法的返回值是布尔值,其中true表示仍在执行某些操作,false表示已完成工作

If you want to experience first hand the joy and wonder that are broadcast receivers, you can follow these links to repositories that I have set up:

如果您想亲身体验广播接收者的喜悦和惊奇,可以通过以下链接访问我建立的存储库:

  1. Custom Broadcast (with manifest declaration)

    自定义广播 (带有清单声明)

  2. Registering Broadcast (without declaring one in the manifest)

    注册广播 (未在清单中声明一个)

  3. LocalBroadcastManager

    LocalBroadcastManager

Broadcast over.

广播过来。

翻译自: https://www.freecodecamp.org/news/android-broadcast-receivers-for-beginners/

android初学者

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/391561.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Android热修复之 - 阿里开源的热补丁

1.1 基本介绍     我们先去github上面了解它https://github.com/alibaba/AndFix 这里就有一个概念那就AndFix.apatch补丁用来修复方法&#xff0c;接下来我们看看到底是怎么实现的。1.2 生成apatch包      假如我们收到了用户上传的崩溃信息&#xff0c;我们改完需要修复…

leetcode 456. 132 模式(单调栈)

给你一个整数数组 nums &#xff0c;数组中共有 n 个整数。132 模式的子序列 由三个整数 nums[i]、nums[j] 和 nums[k] 组成&#xff0c;并同时满足&#xff1a;i < j < k 和 nums[i] < nums[k] < nums[j] 。 如果 nums 中存在 132 模式的子序列 &#xff0c;返回…

seaborn分类数据可视:散点图|箱型图|小提琴图|lv图|柱状图|折线图

一、散点图stripplot( ) 与swarmplot&#xff08;&#xff09; 1.分类散点图stripplot( ) 用法stripplot(xNone, yNone, hueNone, dataNone, orderNone, hue_orderNone,jitterTrue, dodgeFalse, orientNone, colorNone, paletteNone,size5, edgecolor"gray", linewi…

数据图表可视化_数据可视化十大最有用的图表

数据图表可视化分析师每天使用的最佳数据可视化图表列表。 (List of best data visualization charts that Analysts use on a daily basis.) Presenting information or data in a visual format is one of the most effective ways. Researchers have proved that the human …

javascript实现自动添加文本框功能

转自&#xff1a;http://www.cnblogs.com/damonlan/archive/2011/08/03/2126046.html 昨天&#xff0c;我们公司的网络小组决定为公司做一个内部的网站&#xff0c;主要是为员工比如发布公告啊、填写相应信息、投诉、问题等等需求。我那同事给了我以下需求&#xff1a; 1.点击一…

从Mysql slave system lock延迟说开去

本文主要分析 sql thread中system lock出现的原因&#xff0c;但是笔者并明没有系统的学习过master-slave的代码&#xff0c;这也是2018年的一个目标&#xff0c;2018年我都排满了&#xff0c;悲剧。所以如果有错误请指出&#xff0c;也作为一个笔记用于后期学习。同时也给出笔…

传智播客全栈_播客:从家庭学生到自学成才的全栈开发人员

传智播客全栈In this weeks episode of the freeCodeCamp podcast, Abbey chats with Madison Kanna, a full-stack developer who works remotely for Mediavine. Madison describes how homeschooling affected her future learning style, how she tackles imposter syndrom…

leetcode 82. 删除排序链表中的重复元素 II(map)

解题思路 map记录数字出现的次数&#xff0c;出现次数大于1的数字从链表中移除 代码 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val val; }* ListNode(…

python 列表、字典多排序问题

版权声明&#xff1a;本文为博主原创文章&#xff0c;遵循 CC 4.0 by-sa 版权协议&#xff0c;转载请附上原文出处链接和本声明。本文链接&#xff1a;https://blog.csdn.net/justin051/article/details/84289189Python使用sorted函数来排序&#xff1a; l [2,1,3,5,7,3]print…

接facebook广告_Facebook广告分析

接facebook广告Is our company’s Facebook advertising even worth the effort?我们公司的Facebook广告是否值得努力&#xff1f; 题&#xff1a; (QUESTION:) A company would like to know if their advertising is effective. Before you start, yes…. Facebook does ha…

如何创建自定义进度栏

Originally published on www.florin-pop.com最初发布在www.florin-pop.com The theme for week #14 of the Weekly Coding Challenge is: 每周编码挑战第14周的主题是&#xff1a; 进度条 (Progress Bar) A progress bar is used to show how far a user action is still in…

基于SpringBoot的CodeGenerator

title: 基于SpringBoot的CodeGenerator tags: SpringBootMybatis生成器PageHelper categories: springboot date: 2017-11-21 15:13:33背景 目前组织上对于一个基础的crud的框架需求较多 因此选择了SpringBoot作为基础选型。 Spring Boot是由Pivotal团队提供的全新框架&#xf…

seaborn线性关系数据可视化:时间线图|热图|结构化图表可视化

一、线性关系数据可视化lmplot( ) 表示对所统计的数据做散点图&#xff0c;并拟合一个一元线性回归关系。 lmplot(x, y, data, hueNone, colNone, rowNone, paletteNone,col_wrapNone, height5, aspect1,markers"o", sharexTrue,shareyTrue, hue_orderNone, col_orde…

hdu 1257

http://acm.hdu.edu.cn/showproblem.php?pid1257 题意&#xff1a;有个拦截系统&#xff0c;这个系统在最开始可以拦截任意高度的导弹&#xff0c;但是之后只能拦截不超过这个导弹高度的导弹&#xff0c;现在有N个导弹需要拦截&#xff0c;问你最少需要多少个拦截系统 思路&am…

eda可视化_5用于探索性数据分析(EDA)的高级可视化

eda可视化Early morning, a lady comes to meet Sherlock Holmes and Watson. Even before the lady opens her mouth and starts telling the reason for her visit, Sherlock can tell a lot about a person by his sheer power of observation and deduction. Similarly, we…

我的AWS开发人员考试未通过。 现在怎么办?

I have just taken the AWS Certified Developer - Associate Exam on July 1st of 2019. The result? I failed.我刚刚在2019年7月1日参加了AWS认证开发人员-联考。结果如何&#xff1f; 我失败了。 The AWS Certified Developer - Associate (DVA-C01) has a scaled score …

关系数据可视化gephi

表示对象之间的关系&#xff0c;可通过gephi软件实现&#xff0c;软件下载官方地址https://gephi.org/users/download/ 如何来表示两个对象之间的关系&#xff1f; 把对象变成点&#xff0c;点的大小、颜色可以是它的两个参数&#xff0c;两个点之间的关系可以用连线表示。连线…

Hyperledger Fabric 1.0 从零开始(十二)——fabric-sdk-java应用

Hyperledger Fabric 1.0 从零开始&#xff08;十&#xff09;——智能合约&#xff08;参阅&#xff1a;Hyperledger Fabric Chaincode for Operators——实操智能合约&#xff09; Hyperledger Fabric 1.0 从零开始&#xff08;十一&#xff09;——CouchDB&#xff08;参阅&a…

css跑道_如何不超出跑道:计划种子的简单方法

css跑道There’s lots of startup advice floating around. I’m going to give you a very practical one that’s often missed — how to plan your early growth. The seed round is usually devoted to finding your product-market fit, meaning you start with no or li…

将json 填入表格_如何将Google表格用作JSON端点

将json 填入表格UPDATE: 5/13/2020 - New Share Dialog Box steps available below.更新&#xff1a;5/13/2020-下面提供了 新共享对话框步骤。 Thanks Erica H!谢谢埃里卡H&#xff01; Are you building a prototype dynamic web application and need to collaborate with …