1-等到wifi启用即打开?2-等到它真正连接到wifi网络?
您可以为这两个事件创建BroadcastReceiver,然后执行特定操作:
public class WifiStateReceiver extends BroadcastReceiver {
// action for Wi-Fi device status changes (enabled, disabled etc.)
if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
// get actual status of Wi-Fi
int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_UNKNOWN);
if (state == WifiManager.WIFI_STATE_ENABLED) {
// do your stuff
}
...
// similar for WIFI_STATE_DISABLED
}
// action for connectivity changes (connected, disconnected etc.)
if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo ni = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (ni.getState().equals(NetworkInfo.State.CONNECTED)) {
// do your stuff if is connected
}
...
// similar for DISCONNECTED
}
}
如果您想了解更多的连接状态(正在连接、获取 IP 地址等),您需要使用:
networkInfo.getDetailedState();
这也取决于设备上的实际 API 级别。
最后,您需要这些用于 BroadcastReceiver 的 Intent 过滤器:
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.wifi.STATE_CHANGE" />
参考: