androidandroid-networking

Possible to observe network status?


I'm wondering if there's a way to somehow register as an observer for network access (and have some callback function run when the internet is avaliable), or if polling is the only way. Thanks!


Solution

  • You can register receiver:

    //Callback  
    private final BroadcastReceiver mNetworkStateReceiver = new BroadcastReceiver() {
        @Override
            public void onReceive(Context context, Intent intent) {
               //network state changes, you can process it, inforamtion in intent
            }
        };
    
    //registering recievr in actibity or in service
    IntentFilter mNetworkStateFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(mNetworkStateReceiver , mNetworkStateFilter);
    

    Detail at: http://developer.android.com/reference/android/net/ConnectivityManager.html