简体   繁体   English

如何在Android中检测WiFi接入点是否刚刚失去互联网连接

[英]How to detect if WiFi access point has just lost internet connection in Android

I was looking for a way to react a case when: 在以下情况下,我一直在寻找应对情况的方法:

  • I am connected to WiFi 我已连接到WiFi
  • the access point has just lost internet connection (eg the cable from router has been removed) 接入点刚刚失去互联网连接(例如,路由器的电缆已拔出)

In such cases, Android phones or notebooks are notified about that state and showing exclamation mark next to the WiFi icon. 在这种情况下,系统会通知Android手机或笔记本电脑该状态,并在WiFi图标旁边显示感叹号。

Is it possible to be notified about that state in Android API? 是否可以在Android API中收到有关该状态的通知? I was looking in the documentation but not found any. 我在查找文档,但未找到任何文档。

IMPORTANT NOTE: I am not looking for just checking internet connection manually or just listen for changing network connection status as I will not be notified when the WiFi access point that I am connected to has lost the connection. 重要说明:我不是在寻找手动检查互联网连接或只是在侦听更改的网络连接状态,因为当我连接的WiFi接入点失去连接时,不会收到通知。

So regarding above I was trying to just check the changes of the network connection, but as i explained it is not enough for my case: 因此,关于上述内容,我试图仅检查网络连接的更改,但是正如我所解释的那样,这不足以满足我的情况:

override fun onReceive(context: Context, intent: Intent) {
val wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 
DEFAULT_WIFI_STATE_VALUE)
wifiStateSubject.onNext(wifiState)
Timber.d("Current wifi state: $wifiState")
}

You can periodically try to access some resource with low ping and low timeout rate and if it throws some kind of NetworkException you can suppose that connection not available. 您可以定期尝试以低ping和低超时率访问某些资源,如果它引发某种NetworkException,则可以假定该连接不可用。

UPD: UPD:

You can use or inspect this library https://github.com/pwittchen/NetworkEvents 您可以使用或检查此库https://github.com/pwittchen/NetworkEvents

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM