[英]Notify user when Internet connection is lost in android
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.我正在尝试制作一个应用程序,当与 Internet 的连接丢失(移动数据或 wifi)时,我需要通过 toast 通知用户,并且可能会启动另一个活动并在用户返回主要活动时立即返回重新上线。 Can someone please guide me in doing this.
有人可以指导我这样做。 Thank you.
谢谢你。
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
}
Use NetworRequestCallBack provided by the Android to get the Internet connection changes.使用 Android 提供的 NetworRequestCallBack 获取 Internet 连接更改。 https://developer.android.com/reference/android/net/ConnectivityManager.NetworkCallback
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"
}
})
The behaviour you want to achieve can be achieved seamlessly using Reactive Network library.您想要实现的行为可以使用Reactive Network库无缝实现。 If you already use RxJava in your project then it is even more convenient!
如果你已经在项目中使用了 RxJava,那就更方便了!
Here it is documented how you can observe network connectivity https://github.com/pwittchen/ReactiveNetwork#observing-network-connectivity这里记录了如何观察网络连接https://github.com/pwittchen/ReactiveNetwork#observing-network-connectivity
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.