Last active
December 18, 2015 18:18
-
-
Save frankiesardo/5824321 to your computer and use it in GitHub Desktop.
An Android Button that automatically enables itself when the internet connectivity is on and disables when is off.
This file contains hidden or 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
public class NetworkStatusProducerApplication extends Application { | |
Bus bus = BusProvider.get(); | |
NetworkStatus networkStatus; | |
@Override | |
public void onCreate() { | |
super.onCreate(); | |
updateNetworkStatus(); | |
bus.register(this); | |
} | |
public void updateNetworkStatus() { | |
final ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); | |
final android.net.NetworkInfo wifi = connMgr | |
.getNetworkInfo(ConnectivityManager.TYPE_WIFI); | |
final android.net.NetworkInfo mobile = connMgr | |
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); | |
boolean wifiConnected = wifi.isAvailable() | |
&& wifi.getState() == NetworkInfo.State.CONNECTED; | |
boolean mobileConnected = mobile.isAvailable() | |
&& mobile.getState() == NetworkInfo.State.CONNECTED; | |
boolean isConnected = wifiConnected || mobileConnected; | |
networkStatus = new NetworkStatus(isConnected); | |
bus.post(produceNetworkStatus()); | |
} | |
@Produce | |
public NetworkStatus produceNetworkStatus() { | |
return networkStatus; | |
} | |
public static class NetworkStatus { | |
private final boolean connected; | |
public NetworkStatus(boolean connected) { | |
this.connected = connected; | |
} | |
public boolean isConnected() { | |
return connected; | |
} | |
} | |
} |
This file contains hidden or 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
public class NetworkStatusReceiver extends BroadcastReceiver { | |
/** register this receiver with the intents: | |
* <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/> | |
* <action android:name="android.net.wifi.WIFI_STATE_CHANGED"/> | |
*/ | |
@Override | |
public void onReceive(final Context context, final Intent intent) { | |
((NetworkStatusProducerApplication) context.getApplicationContext()).updateNetworkStatus(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment