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
Asked
Active
Viewed 62 times
-1
-
1Possible duplicate of [Android event for internet connectivity state change](https://stackoverflow.com/questions/6169059/android-event-for-internet-connectivity-state-change) – Manoj Perumarath Aug 30 '19 at 09:34
2 Answers
2
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
snachmsm
- 17,866
- 3
- 32
- 74
-
1Thank you for taking the time to answer my question. Your answer was very helpful, thanks. – Lilian Sorlanski Aug 30 '19 at 10:04
0
fun isInternetOncheck(context: Context): Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = cm.activeNetworkInfo
return networkInfo != null && networkInfo.isConnectedOrConnecting
}
if (!NetworkCaller.isInternetOncheck(context!!)) {
println("no internet connection")
} else {
fetchDataFromServer()
}
fetchDataFromServer(){
showProgressbar()
......
......
//code for fetching data
......
......
hideProgressbar()
}
Chirag Rayani
- 309
- 1
- 14
-
Thanks but I don't need to always show the `ProgressBar`, I only need to display while the device is connecting (2-3 seconds). – Lilian Sorlanski Aug 30 '19 at 09:01