broadcast Receivers (Broadcastreceiver)
Broadcast in Android can be divided into two types, standard broadcast and ordered broadcast.
standard Broadcast (normal broadcasts):
is a completely asynchronous broadcast, after the broadcast, all broadcast receivers will almost at the same time receive this broadcast message,
So there is no order of precedence between them. This kind of broadcast is more efficient, but it also means that it cannot be truncated.
Ordered broadcast (orderedbroadcasts):
is a synchronous broadcast, after the broadcast, there will only be a broadcast receiver at the same time to receive this broadcast message, when the
The broadcast will continue to pass after the logic in the broadcast receiver has finished executing. Therefore, the broadcast receivers at this time are sequential, high-priority
Broadcast receiver, and the previous broadcast receiver can also truncate the broadcast being delivered, so that the broadcast receiver
will not be able to receive the broadcast message.
To receive a broadcast, you need to use a broadcast receiver.
There are generally two ways of registering a broadcast, registering it in code and registering it in Androidmanifest.xml, where the former is also known as dynamic registration.
The latter is also known as static registration.
This is the way to collect the radio:
Here is the dynamic registration of monitoring network changes
So how do you create a broadcast receiver? You just need to create a new class, let it inherit from Broadcastreceiver, and override the parent class's
The OnReceive () method is OK. So when a broadcast arrives, the OnReceive () method is executed, and the specific logic can be
Processing in the law. So let's start by dynamically registering a program that listens to network changes and learns the basics of broadcasting receivers.
Use it. Create a new Broadcasttest project, and then modify the code in the mainactivity:
Public classMainactivityextendsActivity {PrivateIntentfilter Intentfilter; PrivateNetworkchangereceiver Networkchangereceiver; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Intentfilter=NewIntentfilter (); Intentfilter.addaction ("Android.net.conn.CONNECTIVITY_CHANGE"); Networkchangereceiver=NewNetworkchangereceiver (); Registerreceiver (Networkchangereceiver, Intentfilter); } @Overrideprotected voidOnDestroy () {Super. OnDestroy (); Unregisterreceiver (Networkchangereceiver); } classNetworkchangereceiverextendsBroadcastreceiver {@Override Public voidOnReceive (Context context, Intent Intent) {toast.maketext (context,"Network Changes", Toast.length_short). Show (); } }}
As you can see, we define an inner class networkchangereceiver in Mainactivity, which is inherited from
Broadcastreceiver, and overrides the OnReceive () method of the parent class. So whenever the network state changes, OnReceive ()
method is executed, and this is simply a hint of a text message using a toast. Then observe the OnCreate () method, first we
An instance of Intentfilter was created and a value of Android.net.conn.CONNECTIVITY_CHANGE was added to it
Action, why do you want to add this value? Because when the network state changes, the system emits exactly one value
Android.net.conn.CONNECTIVITY_ change broadcast, which means our broadcast receivers want to listen to what broadcasts,
Just add the appropriate action here. Next, you create an instance of Networkchangereceiver, and then call
The Registerreceiver () method is registered, and the instance of Networkchangereceiver and the instance of Intentfilter are passed in.
So that Networkchangereceiver will receive all broadcasts with a value of Android.net.conn.CONNECTIVITY_CHANGE,
It also realizes the function of monitoring network change. Finally, remember that the dynamic registration of the broadcast receiver must be unregistered to do, here we are in
The OnDestroy () method is implemented by calling the Unregisterreceiver () method. Overall, the code is very simple, and now
Run the program. First you will receive a broadcast when the registration is complete, and then press the Home button to return to the main screen (note that you cannot press the back key
, otherwise the OnDestroy () method executes), then press the menu key →systemsettings→datausage Enter the data usage details
interface, and then try switching mobiledata to start and disable the network, you'll see a toast reminding you that the network has changed. But only
is to remind the network has changed is not enough humane, it is best to tell the user is currently a network or no network, so we also need
Further optimizations are made to the above code. To modify the code in Mainactivity:
Public classMainactivityextendsActivity {classNetworkchangereceiverextendsBroadcastreceiver {@Override Public voidOnReceive (Context context, Intent Intent) {Connectivitymanager ConnectionManager=(Connectivitymanager) Getsystemservice (Context.connectivity_service); Networkinfonetworkinfo=Connectionmanager.getactivenetworkinfo (); if(Networkinfo! =NULL&&networkinfo.isavailable ()) {Toast.maketext (context,"Network is available", Toast.length_short). Show (); } Else{toast.maketext (context,"Network is unavailable", Toast.length_short). Show (); } } }}
In the OnReceive () method, the Connectivitymanager is first obtained by the Get Getsystemservice () method.
instance, which is a system service class dedicated to managing network connections. Then call it's Getactivenetworkinfo ()
Method can get the instance of Networkinfo, then call Networkinfo's IsAvailable () method, can judge
Out there is currently a network, and finally we will be toast to the user to prompt.
Also be aware that:
Android system to ensure the security of the application, if the program needs to access some of the system's shutdown
Key information, you must declare permissions in the configuration file, or the program will crash directly, such as the query system network
State is required to declare permissions. Open the Androidmanifest.xml file, add the following permissions to query the system
Network Status:
<Manifestxmlns:android= "Http://schemas.android.com/apk/res/android" Package= "Com.example.broadcasttest"Android:versioncode= "1"Android:versionname= "1.0"><USES-SDKandroid:minsdkversion= "+"android:targetsdkversion= "+" /><uses-permissionAndroid:name= "Android.permission.ACCESS_NETWORK_STATE" />...</Manifest>
You can then view these declared permissions in the Android app.
Now run again and see the hints from the system.
And there's one.
Static registration implementation Start-up I'm not so sure about that, so I'm not going to write. I decided to write it down.
2, static registration Implementation boot: (link)
The broadcasting mechanism of Android development