如何检测何时在 Android 中建立了 WIFI 连接? [英] How to detect when WIFI Connection has been established in Android?
问题描述
我需要检测何时通过 WIFI 连接网络.发送什么广播以建立有效的网络连接.我需要验证 HTTP 的有效网络连接是否存在.我应该听什么以及我需要做哪些额外的测试才能知道存在有效的连接.
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.
推荐答案
您可以注册一个 BroadcastReceiver
在建立 WiFi 连接(或连接更改)时收到通知.
You can register a BroadcastReceiver
to be notified when a WiFi connection is established (or if the connection changed).
注册BroadcastReceiver
:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
然后在你的 BroadcastReceiver
中做这样的事情:
And then in your BroadcastReceiver
do something like this:
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
if (intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)) {
//do stuff
} else {
// wifi connection was lost
}
}
}
有关详细信息,请参阅 BroadcastReceiver
的文档 和 WifiManager
For more info, see the documentation for BroadcastReceiver
and WifiManager
当然在此之前您应该检查设备是否已经连接到WiFi.
Of course you should check whether the device is already connected to WiFi before this.
感谢ban-geoengineering,这里有一个检查设备是否已经连接的方法:
Thanks to ban-geoengineering, here's a method to check whether the device is already connected:
private boolean isConnectedViaWifi() {
ConnectivityManager connectivityManager = (ConnectivityManager) appObj.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return mWifi.isConnected();
}
这篇关于如何检测何时在 Android 中建立了 WIFI 连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!