Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Properly control Android service state based on Wifi status
private void registerConnectivityChange() {
BroadcastReceiver connectionReceiver = new BroadcastReceiver() {
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
if (networkInfo.isConnected()) {
// Wifi is connected
} else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
NetworkInfo networkInfo = intent
if (networkInfo.getDetailedState() == DetailedState.DISCONNECTED) {
// Wifi is down
IntentFilter wifiEvents = new IntentFilter("");
registerReceiver(connectionReceiver, wifiEvents);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment