Android monitoring network status

Source: Internet
Author: User

 

During Android network application development, it is often necessary to determine whether the network connection is available. Therefore, it is often necessary to listen to changes in the network status. For android network status monitoring, BroadcastReceiver can be used to receive broadcasts with network status changes. The specific implementation is as follows:

@ Override

Public void onReceive (Context context, Intent intent ){

Log. e (TAG, "network status change ");

 

Boolean success = false;

 

// Obtain the Network Connection Service

ConnectivityManager connManager = (ConnectivityManager) getSystemService (CONNECTIVITY_SERVICE );

// State state = connManager. getActiveNetworkInfo (). getState ();

State state = connManager. getNetworkInfo (

ConnectivityManager. TYPE_WIFI). getState (); // gets the network connection status

If (State. CONNECTED = state) {// determine whether the Wi-Fi network is in use

Success = true;

}

 

State = connManager. getNetworkInfo (

ConnectivityManager. TYPE_MOBILE). getState (); // gets the network connection status

If (State. CONNECTED! = State) {// determine whether the GPRS network is being used

Success = true;

}

 

If (! Success ){

Toast. makeText (LocationMapActivity. this, "your network connection has been interrupted", Toast. LENGTH_LONG). show ();

}

 

}

In onCreate of Activity:

// Register a network listener

IntentFilter filter = new IntentFilter ();

Filter. addAction (ConnectivityManager. CONNECTIVITY_ACTION );

RegisterReceiver (mNetworkStateReceiver, filter );

// In onDestroy of Activity :'

 

UnregisterReceiver (mNetworkStateReceiver); // cancel the listener

 

Author: crane

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.