Last active
August 29, 2015 13:56
-
-
Save chris-piekarski/9334185 to your computer and use it in GitHub Desktop.
Properly control Android service state based on Wifi status
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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