Reputation: 4306
I need to know how I can detect a switch in Wi-Fi networks, albeit automatically or manually, it doesn't matter. Is there some kind of intent being broadcasted throughout the system when a switch is detected? Or do I have to manually check if a new network is selected by calling a method on a ConnectivityManager?
Upvotes: 1
Views: 7575
Reputation: 4306
At this point in time, I have fixed this like this (haven't fully tested it yet as I don't have a second network available at the moment):
I extended the BroadcastReceiver class
private class NetworkSwitcher extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
return;
}
NetworkInfo networkInfo =
(NetworkInfo)intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
Log.d(TAG, "Network type: " + networkInfo.getTypeName() +
" Network subtype: " + networkInfo.getSubtypeName());
getOwnIpAddress();
mClient.updateUnicastSocket(mOwnAddress, mUnicastPort);
}
}
else {
Log.e(TAG, "Network connection lost");
}
}
}
I register this class as a receiver with a filter set to the ConnectivityManager.CONNECTIVITY_ACTION
intent (setting it in onResume()
and releasing it in onPause()
). This ought to catch any automatic Wi-Fi network switch. The getOwnIpAddress
retrieves the device's IP address from the WifiManager
.
I've also found that it works when I return to the activity from another activity.
Upvotes: 7