Use of BroadcastReceiver (Asynchronous Receiver broadcast Intent) in Android

Source: Internet
Author: User

Introduction to Broadcast Receiver
Broadcast Receiver is one of the five major Android components and is frequently used.
It is used to receive broadcast Intent asynchronously. The broadcast Intent is sent by calling Context. sendBroadcast () and BroadcastReceiver are used to receive broadcast Intent asynchronously. sendBroadcast (), Context. sendOrderedBroadcast () or Context. sendStickyBroadcast. Generally, a broadcast Intent can be received by multiple broadcast recipients subscribed to this Intent. The broadcast receiver is similar to the Topic Message Receiver in JMS.
A broadcast receiver can only receive broadcasts and respond to notifications. Many broadcasts are produced by system code. for example, notifications of time zone changes, insufficient battery, user-changed language preferences, or startup.
The broadcast receiver does not have a user interface, but it can start an Activity for the information they receive or use icationicationmanager to notify the user.
Lifecycle
A BroadcastReceiver object is valid only when onReceive (Context, Intent) is called. After the function is returned, this object is invalid and the lifecycle ends.
Therefore, we can see from this feature that the onReceive (Context, Intent) function called cannot have too many time-consuming operations and cannot be executed using threads. For time-consuming operations, start service. Because BroadcastReceiver may be invalid when other asynchronous operations return results.
Example of network status change monitoring
The following example shows how to use BroadcastReceiver.
NetworkStateReceiver: receives the Broadcast from the system when the network status changes. Copy codeThe Code is as follows: package com. example. networkbroadcastreceiver;
Import android. content. BroadcastReceiver;
Import android. content. Context;
Import android. content. Intent;
Import android.net. ConnectivityManager;
Import android.net. NetworkInfo;
Import android. util. Log;
Import android. widget. Toast;
Public class NetworkStateReceiver extends BroadcastReceiver {
Private static final String TAG = "NetworkStateReceiver ";
@ Override
Public void onReceive (Context context, Intent intent ){
Log. I (TAG, "network state changed .");
If (! IsNetworkAvailable (context )){
Toast. makeText (context, "network disconnected! ", 0). show ();
}
Else Toast. makeText (context, "network connected! ", 0). show ();
}
/**
* Whether the Network is available
*
* @ Param context
* @ Return
*/
Public static boolean isNetworkAvailable (Context context ){
ConnectivityManager mgr = (ConnectivityManager) context. getSystemService (Context. CONNECTIVITY_SERVICE );
NetworkInfo [] info = mgr. getAllNetworkInfo ();
If (info! = Null ){
For (int I = 0; I <info. length; I ++ ){
If (info [I]. getState () = NetworkInfo. State. CONNECTED ){
Return true;
}
}
}
Return false;
}
}

MainActivity:Copy codeThe Code is as follows: package com. example. networkbroadcastreceiver;
Import android. OS. Bundle;
Import android. app. Activity;
Import android. view. Menu;
Public class MainActivity extends Activity {
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );

Static registration and Dynamic Registration
Register the BroadcastReceiver.
Static registration needs to modify the manifest file, which is also my method.
AddCopy codeThe Code is as follows: <SPAN style = "FONT-SIZE: 14px"> <Cycler android: name = ". NetworkStateReceiver">
<Intent-filter>
<Action android: name = "android.net. conn. CONNECTIVITY_CHANGE"/>
<Category android: name = "android. intent. category. DEFAULT"/>
</Intent-filter>
</Cycler> </SPAN>

Dynamic Registration is required (not debugged ):
1. In onCreate of Activity:
// Register a network listener
IntentFilter filter = new IntentFilter ();
Filter. addAction (ConnectivityManager. CONNECTIVITY_ACTION );
RegisterReceiver (mNetworkStateReceiver, filter );
2. In onDestroy of Activity:
// Cancel the listener
UnregisterReceiver (mNetworkStateReceiver );
Final effect:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.