如何检测,当WIFI连接已经建立的Android? [英] 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.
推荐答案
您可以注册一个<一个href="http://developer.android.com/reference/android/content/BroadcastReceiver.html"><$c$c>BroadcastReceiver$c$c>得到通知时,建立一个无线连接(或者连接更改)。
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
做这样的事情:
@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
}
}
}
有关更多信息,请参阅文件<一个href="http://developer.android.com/reference/android/content/BroadcastReceiver.html"><$c$c>BroadcastReceiver$c$c>和<一href="http://developer.android.com/reference/android/net/wifi/WifiManager.html"><$c$c>WifiManager$c$c>
For more info, see the documentation for BroadcastReceiver
and WifiManager
当然,你应该检查设备是否已连接到无线网络在此之前。
Of course you should check whether the device is already connected to WiFi before this.
编辑: 由于禁止,地球工程,这里有一个方法来检查设备是否已连接:
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();
}
这篇关于如何检测,当WIFI连接已经建立的Android?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!