Search code examples
androidandroid-networking

What event is triggered when WiFi connection of the peer device is turned off in android ecosystem?


What is the event triggered when WiFi connection is turned off by the peer device. Is there any way that the host device gets a callback for example, onConnectionStateChange() or similar?


Solution

  • this example suits your need.

    What you're looking for is call broadcast receiver. basically, you create a custom broadcast receiver that will receive message on some actions. you define those action in an intent filter :

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    

    then register your receiver on this intent filter :

    registerReceiver(wifiWatcher, intentFilter);
    

    and your receiver will implement the onReceive method :

    public void onReceive( Context context, Intent intent )
    

    You'll have to check connectivity on this onReceive method using :

    ConnectivityManager conMngr = (ConnectivityManager)this.getSystemService(this.CONNECTIVITY_SERVICE);
    android.net.NetworkInfo wifi = conMngr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    android.net.NetworkInfo mobile = conMngr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    

    to do that, you need to add those permissions in your manifest :

    <user-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <user-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    

    hope that helps.