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.pswp.cn/news/391561.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391561.shtml
英文地址,請注明出處:http://en.pswp.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 …