Search code examples
androidandroid-wifiandroid-progressbar

How know when a device is connecting to WiFi/Mobile/Internet?


I have button that needs to get some data from a back-end server. The button is disabled while the device is not connected to WiFi/Mobile/Internet. The problem is that when pressing the WiFi button it takes some time till it actually connects (2-3 seconds). How to know when the devices is connecting so I can display a ProgressBar in that periode of time? Thanks


Solution

  • plenty of methods in THIS SO question. In short you should use BroadcastReceiver with IntentFilter with ConnectivityManager.CONNECTIVITY_ACTION action. Check out NetworkInfo.State DOC and pick appriopiate for reporting (create own listener with needed callbacks)

    if you can afford only newer APIs then you can use NetworkCallback, in DOC you can see all methods, use appriopiate. But I doubt sadly due to Android fragmentation, still better way is mentioned first one.

    Also remember that since Android N this broadcast won't fire when was declared in manifest, use Java examples and (un)register with Activity lifecycle