Android monitor Android monitor system network connection open or close implementation code

Source: Internet
Author: User

This article introduces the implementation of the network connection open or close of the listening system in Android. Need a friend to reference under

Very simple, so look directly at the code

Copy CodeThe code is as follows:
Package xxx;

Import Android.content.BroadcastReceiver;
Import Android.content.Context;
Import android.content.Intent;
Import Android.net.ConnectivityManager;
Import Android.net.NetworkInfo;

Copy CodeThe code is as follows:
public class Netstatereceiver extends Broadcastreceiver {

@Override
public void OnReceive (context context, Intent Intent) {
Connectivitymanager manager = (Connectivitymanager) context
. Getsystemservice (Context.connectivity_service);
Networkinfo GPRS = Manager
. Getnetworkinfo (Connectivitymanager.type_mobile);
Networkinfo WiFi = Manager
. Getnetworkinfo (Connectivitymanager.type_wifi);
if (!gprs.isconnected () &&!wifi.isconnected ()) {
Network closed
} else {
Network opend

}
}

}


The code customizes a broadcastreceiver, which is an event that wants to listen for changes in the network settings.

Register for monitoring in the manifest file.

Copy CodeThe code is as follows:
<receiver android:name= "Xxx.netstatereceiver" >
<intent-filter>
<action android:name= "Android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>


You also need to include permission information.

Copy CodeThe code is as follows:
<uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE"/>

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.