Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Properly control Android service state based on Wifi status
private void registerConnectivityChange() {
BroadcastReceiver connectionReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// When just using the ConnectivityManager you can get identical intents
// twice within one second. So we need to use the WifiManager & ConnectivityManager
// to determine true state
if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo networkInfo = intent
.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
// Wifi is connected
setWifiUp();
}
} else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
NetworkInfo networkInfo = intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo.getDetailedState() == DetailedState.DISCONNECTED) {
// Wifi is down
setWifiDown();
}
}
}
};
IntentFilter wifiEvents = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
wifiEvents.addAction("android.net.wifi.STATE_CHANGE");
registerReceiver(connectionReceiver, wifiEvents);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment