I am trying to make an app where I need to notify the user via a toast when the connection to the internet is lost(either mobile data or wifi) and possibly launch another activity and return back to the main activity as soon as the user is back online. Can someone please guide me in doing this. Thank you.
Asked
Active
Viewed 1,084 times
1
-
This should help https://stackoverflow.com/questions/33584746/show-toast-when-there-is-no-internet-access-android – Dipansh Khandelwal Jun 30 '20 at 14:34
3 Answers
2
Use NetworRequestCallBack provided by the Android to get the Internet connection changes. https://developer.android.com/reference/android/net/ConnectivityManager.NetworkCallback
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkRequest = NetworkRequest.Builder().build()
connectivityManager.registerNetworkCallback(networkRequest, object :
ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
// "Net connected"
}
override fun onLost(network: Network) {
super.onLost(network)
// "Network lost"
}
})

Alpha 1
- 4,118
- 2
- 17
- 23
0
You can use this to check if network is available
public static boolean isNetworkAvailable(Context activity) {
ConnectivityManager connectivityManager
= (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Use the above method as
if(isNetworkAvailable(context)){
//Network is available}
else {
//Network Unavailable
}

MrinmoyMk
- 551
- 7
- 21
-
Thank you for your help but this is only working once but I need to notify user as many times the network is disconnected – MaskedCarrot Jun 30 '20 at 14:58
-
You can do call this method everytime the user touches any part of your app. This way everytime before doing any task you can notify the users – MrinmoyMk Jun 30 '20 at 15:27
0
The behaviour you want to achieve can be achieved seamlessly using Reactive Network library. If you already use RxJava in your project then it is even more convenient!
Here it is documented how you can observe network connectivity https://github.com/pwittchen/ReactiveNetwork#observing-network-connectivity

Filip Sollár
- 91
- 1
- 5