Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An Android Button that automatically enables itself when the internet connectivity is on and disables when is off.
public class NetworkButton extends Button {
// See Otto's sample application for how BusProvider works. Any mechanism
// for getting a singleton instance will work.
Bus bus = BusProvider.get();
public NetworkButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NetworkButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
bus.register(this);
}
@Override
protected void onDetachedFromWindow() {
bus.unregister(this);
super.onDetachedFromWindow();
}
@Subscribe
public void onNetworkStatusUpdated(NetworkStatus status) {
setEnabled(status.isConnected());
}
}
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;
}
}
}
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