The use of Broadcastreceiver (asynchronous receive broadcast intent) in Android _android

Source: Internet
Author: User
Broadcast Receiver Introduction
Broadcast receiver is one of the top five components of Android and is used very frequently.
Used for asynchronous reception of broadcast intent, broadcast intent sent by calling Context.sendbroadcast (), broadcast Receiver (BROADCASTRECEIVER) to receive broadcast intent asynchronously, The broadcast intent is implemented by calling Context.sendbroadcast (), Context.sendorderedbroadcast (), or context.sendstickybroadcast (). Usually a broadcast intent can be received by multiple broadcast receivers subscribing to this intent, and the broadcast receiver is similar to the topic message receiver in JMS.
Broadcast receivers can only receive broadcasts, respond to broadcast notifications, and many broadcasts are generated from system code. Such as: Notice of time zone change, low battery power, user changed language preference or boot start, etc.
Broadcast receivers do not have a user interface, but they can receive information to initiate an activity or use Notificationmanager to notify the user.
Life cycle
A Broadcastreceiver object is valid only if it is invoked onreceive (context, Intent), and when returned from the function, the object is invalid, ending the lifecycle.
Therefore, it can be seen from this feature that in the invoked OnReceive (context, Intent) function, there can be no too time-consuming operation, can not use the thread to execute. For time-consuming operations, please start service to complete. Because the broadcastreceiver may not be valid when the result returned by another asynchronous operation is obtained.
example of monitoring network state changes
The following is an example to use Broadcastreceiver.
Networkstatereceiver: The broadcast that the system emits when receiving network state changes.
Copy Code code 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 Code code 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
After you have written the broadcastreceiver, register it.
Static registration needs to modify the manifest file, is also the method I used.
Add to
Copy Code code as follows:

<span style= "font-size:14px" ><receiver android:name= ". Networkstatereceiver ">
<intent-filter>
<action android:name= "Android.net.conn.CONNECTIVITY_CHANGE"/>
<category android:name= "Android.intent.category.DEFAULT"/>
</intent-filter>
</receiver></SPAN>

Dynamic registration needs to be done (not debugged):
1. In the oncreate of the activity:
Registering for network monitoring
Intentfilter filter = new Intentfilter ();
Filter.addaction (connectivitymanager.connectivity_action);
Registerreceiver (mnetworkstatereceiver, filter);
2. In the OnDestroy of activity:
Cancel Listening
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.