1

Would registering the following listener notify your app when internet connectivity changes or only when network connectivity changes?

I need to get notified when the internet goes on or off even if the phone is still connected to the same network.

<receiver
        android:name="com.internetconnection_demo.InternetConnector_Receiver"
        android:enabled="true" >
        <intent-filter>

            <!-- Intent filters for broadcast receiver -->
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            <action android:name="android.net.wifi.STATE_CHANGE" />
        </intent-filter>
    </receiver>
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
user1603602
  • 984
  • 1
  • 7
  • 11

1 Answers1

0

If you are on Lollipop (API 21) or later, I wouldn't go the BroadcastReceiver route. Try something like this instead:

fun monitorWifiConnection() {
    var connectivityManager: ConnectivityManager = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
    val builder = NetworkRequest.Builder()
            .addTransportType(android.net.NetworkCapabilities.TRANSPORT_WIFI)
    connectivityManager.registerNetworkCallback(builder.build(), getConnectivityManagerCallback())
}

private fun getConnectivityManagerCallback(): ConnectivityManager.NetworkCallback {
    connectivityManagerCallback = object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network?) {
            //Connected to wifi
        }

        override fun onLost(network: Network?) {
            //Lost connection to wifi
        }
    }
    return connectivityManagerCallback
}

By excluding the NetworkCapabilities.TRANSPORT_CELLULAR option and including NetworkCapabilities.TRANSPORT_WIFI you should get notifications about the wifi connection exclusively.

rhpekarek
  • 167
  • 9
  • But would this trigger the callback on Internet on/off even if I'm still connected to the WIFI? – user1603602 Dec 11 '18 at 20:09
  • Do you mean the cellular network? See the last note I added below the code snippet. You can choose to monitor cellular network or wifi or both. This request only monitors the wifi. – rhpekarek Dec 11 '18 at 20:11
  • Let's say the following scenario happened. - I'm connected to my wifi at home. - I'm still connected to the wifi, but the wifi access point itself lost internet connectivity. Would the callback happen in this case? – user1603602 Dec 11 '18 at 20:31
  • Yes that's how it should function – rhpekarek Dec 11 '18 at 20:34
  • I think NET_CAPABILITY_VALIDATED flag might be required on top (only API 23+) cf. https://stackoverflow.com/a/41063539/93974 – nuKs Mar 05 '20 at 18:17