Skip to content Skip to sidebar Skip to footer

Efficient Approach To Continuously Check Whether Internet Connection Is Available In Android

Possible Duplicate: How can I monitor the network connection status in Android? I need to continuously check whether the internet is connected or not and update the text area ac

Solution 1:

do it with a receiver. you can be notified about network state change. for example,

privateBroadcastReceivernetworkReceiver=newBroadcastReceiver {
    @OverridepublicvoidonReceive(Context context, Intent intent) {
     super.onReceive(context, intent);
     if(intent.getExtras()!=null) {
        NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
        if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
            // we're connected
        }
     }
     // we're not connected 
   }
}

register this in your onResume(), and unregister on onPause().

@OverrideprotectedvoidonPause() {
    super.onPause();
    unregisterReceiver(networkReceiver);
}

@OverrideprotectedvoidonResume() {
    super.onResume();
    IntentFilter filter = newIntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(networkReceiver, filter);
}

additionally, to obtain the initial state before your receiver has been registered, call this in your onResume() method,

publicbooleanisNetworkConnected() {
        ConnectivityManagercm=
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfonetInfo= cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            returntrue;
        }
        returnfalse;
    }

make sure your app requests this permission,

<uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE" />

Solution 2:

You don't need to constantly ask the OS if there is a network connection. Simply check whether a connection exists in onResume() and then use a BroadcastReceiver to listen for the CONNECTIVITY_ACTION Intent from the ConnectivityManager when the connection is changed and check EXTRA_NO_CONNECTIVITY.

Post a Comment for "Efficient Approach To Continuously Check Whether Internet Connection Is Available In Android"