I need to detect when I have network connectivity over WIFI. What broadcast is sent to establish that a valid network connection has been made. I need to validate that a valid network connection for HTTP exists. What should I listen for and what additional tests do I need to make to know that a valid connection exists.
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
相关文章
- android开发 怎么把图片放入drawable的文件夹下
- android上如何获取/storage/emulated/下的文件列表
- androidStudio有个箭头不认识
- SQLite不能创建表
- Windows - Android SDK manager not listing any plat
- Animate Recycler View grid when number of columns
- Why is the app closing suddenly without showing an
- Android OverlayItem.setMarker(): Change the marker
You can register a
BroadcastReceiver
to be notified when a WiFi connection is established (or if the connection changed).Register the
BroadcastReceiver
:And then in your
BroadcastReceiver
do something like this:For more info, see the documentation for
BroadcastReceiver
andWifiManager
Of course you should check whether the device is already connected to WiFi before this.
EDIT: Thanks to ban-geoengineering, here's a method to check whether the device is already connected:
The best that worked for me:
AndroidManifest
BroadcastReceiver class
Permissions
This code does not require permission at all. It is restricted only to Wi-Fi network connectivity state changes (any other network is not taken into account). The receiver is statically published in the AndroidManifest.xml file and does not need to be exported as it will be invoked by the system
protected broadcast
,NETWORK_STATE_CHANGED_ACTION
, at every network connectivity state change.AndroidManifest:
BroadcastReceiver class:
Permissions:
I used this code:
Android O removed the possibility to receive the implicit broadcasts for a wifi state change. So if your app is closed, you'll not be able to receive them. The new
WorkManager
has the ability to run when your app is closed, so I've experimented a bit with it and it seems to work quite well:Add this to your dependencies:
WifiConnectWorker.kt
MainActivity.kt
Keep in mind that this was just a quick test for a one-time notification. There is more work to do to always get notified when WiFi is turned on and off.
PS: When the app is force quit, the worker is not started, it seems
WorkManager
is canceling the requests then.I have two methods to detect WIFI connection receiving the application context:
1)my old method
2)my New method (I´m currently using this method):