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