Effective Approach to Continuously Check Internet Connection Availability in Android

Possible duplicate:
How to control network connection status in Android?

I need to constantly check whether the Internet is connected or not, and update the text area with the appropriate message. Now, if I create asynctask , it will execute once and stop, which is not what I want. I want to constantly check every time, and obviously this should not be in the main thread. So Service would not be a good choice either. Can anyone help me. What is the best and most effective approach to this. Thanks

+5
source share
2 answers

. . ,

private BroadcastReceiver networkReceiver = new BroadcastReceiver {
    @Override
    public void onReceive(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 
   }
}

onResume() onPause().

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(networkReceiver);
}

@Override
protected void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(networkReceiver, filter);
}

, , , onResume(),

public boolean isNetworkConnected() {
        ConnectivityManager cm =
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }

, ,

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

, . , onResume(), BroadcastReceiver CONNECTIVITY_ACTION ConnectivityManager EXTRA_NO_CONNECTIVITY.

+2

All Articles