Search code examples
androidbroadcastreceiverandroid-wifiandroid-jobschedulergcm-network-manager

Is there any ways to detect the exact time that user turns off WIFI or Data?


  1. I searched and it turns out that Broadcast Receiver is not recommended for the target over N.

  2. I found out GCMNetworkManager. And it is also depreciated.

  3. I also checked JobScheduler. However, its behaviour is not something that I want to implement.

The only way that I can implement among the three is checking the internet status periodically.

However, I don't want it. What I want is detecting the event when user turns them off or on. And then, I'd like to show a dialog to make sure the user turn it on again.

My college who makes iOS says, he uses Observer for his iOS app. And said maybe Android is the same.

Is there any way to make it possible?


Solution

  • You could consider those in Manifest.

            <receiver android:name="receiver.NetworkChangeReceiver">
                <intent-filter>
                    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                    <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
                </intent-filter>
            </receiver>
    

    However, those are deprecated.

    Instead, you can declare it programmatically.

    1. Create a receiver class.
    class NetworkChangeReceiver : BroadcastReceiver() {
        var dialog: Dialog? = null
    
        override fun onReceive(context: Context, intent: Intent) {
            val isConnected = NetworkUtil.getConnectivityStatusString(context)
    
            Toast.makeText(context, "Intere State Changed: $isConnected", Toast.LENGTH_SHORT).show()
        }
    }
    
    1. In your Activity.
    // Internet Check Receiver
    val intentFilter = IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")
    this.registerReceiver(NetworkChangeReceiver(), intentFilter)