您可以收听wifi的连接更改,并根据该事件采取行动以禁用wifi
private ConnectivityManager connectionManager;
boolean previousConnectivityStatus;
private WifiManager wifiManager;
/* Register Connectivity Receiver */
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
context.registerReceiver(networkBroadcastReceiver, intentFilter);
/* Register Wifi State Listener */
IntentFilter wifiStateIntentFilter = new IntentFilter();
wifiStateIntentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
context.registerReceiver(wifiStateReceiver, wifiStateIntentFilter);
connectionManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
private BroadcastReceiver wifiStateReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
Utility.traceM("NetworkController.wifiStateReceiver.new BroadcastReceiver() {...}::onReceive");
int extraWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
switch (extraWifiState)
{
case WifiManager.WIFI_STATE_DISABLED:
{
Utility.trace("Broadcast Wifi State Disabled");
if(isWifiStateEventsEnabled)
{
EventBus.getDefault().post(new NetworkEvent(NetworkEventType.WIFI_DISABLED));
}
break;
}
case WifiManager.WIFI_STATE_ENABLED:
{
Utility.trace("Broadcast Wifi State Enabled");
if(isWifiStateEventsEnabled)
{
EventBus.getDefault().post(new NetworkEvent(NetworkEventType.WIFI_ENABLED));
}
break;
}
}
}
};
private BroadcastReceiver networkBroadcastReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
Utility.traceM("NetworkController.networkBroadcastReceiver.new BroadcastReceiver() {...}::onReceive");
boolean connectivityStatus = isInternetConnectivityAvailable();
if (previousConnectivityStatus != connectivityStatus)
{
if (connectivityStatus)
{
previousConnectivityStatus = true;
Utility.trace("Broadcast Internet Available");
EventBus.getDefault().post(new NetworkEvent(NetworkEventType.INTERNET_CONNECTED));
}
else
{
previousConnectivityStatus = false;
Utility.trace("Broadcast Internet Disconnected");
EventBus.getDefault().post(new NetworkEvent(NetworkEventType.INTERNET_DISCONNECTED));
}
}
}
};