初学者java编译器_初学者广播接收器

初学者java编译器

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? 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.

假设您有一个依赖稳定互联网连接的应用程序。 您希望您的应用程序在Internet连接更改时得到通知。 你是怎样做的? 一种可能的解决方案是始终检查互联网连接的服务。 由于各种原因,此实现都是不好的,因此我们甚至不会考虑。 解决此问题的方法是广播接收器,它将侦听您告诉它的更改。 无论您的应用程序处于什么状态,广播接收器始终会收到广播通知。 您的应用程序当前正在运行,在后台运行还是根本不运行都没有关系。

背景 (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注册实例来动态地进行(这称为上下文注册)

public abstract Intent registerReceiver (BroadcastReceiver receiver, 
                IntentFilter filter);


实作 (Implementation)

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:

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

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

⚠️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:

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

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

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

@Override
protected void onStop() {
  super.onStop();
  unregisterReceiver(myBroadcastReceiver);
}
广播事件 (Broadcasting An Event)

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.Example of sending a custom broadcast

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

https://giphy.com/gifs/23gUJhHyWkXEwl7UYV/html5

https://giphy.com/gifs/23gUJhHyWkXEwl7UYV/html5



陷阱和注意事项 (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_PictureAction_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/broadcast-receivers-for-beginners/

初学者java编译器

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值