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:
有兩種聲明接收方的方法:
- 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:
有三種發送廣播的方法:
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 方法,請確保一次僅將廣播發送到一個接收機。 每個廣播可以依次將數據傳遞到其后的廣播,或停止將廣播傳播到隨后的接收器
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與上述方法類似,但有一個區別。 所有廣播接收器都接收到該消息,并且彼此不依賴
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:
如果您想親身體驗廣播接收者的喜悅和驚奇,可以通過以下鏈接訪問我建立的存儲庫:
Custom Broadcast (with manifest declaration)
自定義廣播 (帶有清單聲明)
Registering Broadcast (without declaring one in the manifest)
注冊廣播 (未在清單中聲明一個)
LocalBroadcastManager
LocalBroadcastManager
Broadcast over.
廣播過來。
翻譯自: https://www.freecodecamp.org/news/android-broadcast-receivers-for-beginners/
android初學者