Connection Detection Using LiveData — Android

It is important to be connected.

Mostly in all of our apps, something or the other depends on the Internet. Whether it is API call, syncing data in background or updating UI based on Internet state, we need to be informed as soon as the Internet state changes.

We do this generally in following manner:

  1. By checking the Internet connection state statically at run time.

2. Creating background service and sending data to our activity/fragments for any change detected.

First method has limitation of not being real time. It tells you about the Internet state only when you ask for it.

Second method requires implementation of broadcast receiver and managing its life cycle, creating bound service and manage its life cycle again.

So what do we do? How can we have safer way of making the connection detection simple, life cycle aware and real time?

With the release of architecture components, we’ve LiveData which we can use to simply connection detection.

LiveData is life cycle aware and can manage the life cycle efficiently.

So let’s take a look on how we’ll do it.

  1. Create a ConnectionLiveData class.
public class ConnectionLiveData extends LiveData<ConnectionModel>{}

2. ConnectionModel contains the type and connected state.

public class ConnectionModel {

private int type;
private boolean isConnected;

public ConnectionModel(int type, boolean isConnected) {
this.type = type;
this.isConnected = isConnected;
}

public int getType() {
return type;
}

public boolean getIsConnected() {
return isConnected;
}
}

3. Create a broadcast receiver to listen for any state change. Register and unregister it with LiveData lifecycle.

public class ConnectionLiveData extends LiveData<ConnectionModel> {

private Context context;

public ConnectionLiveData(Context context) {
this.context = context;
}

@Override
protected void onActive() {
super.onActive();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(networkReceiver, filter);
}

@Override
protected void onInactive() {
super.onInactive();
context.unregisterReceiver(networkReceiver);
}

private BroadcastReceiver networkReceiver = new BroadcastReceiver() {
@SuppressWarnings("deprecation")
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getExtras()!=null) {
NetworkInfo activeNetwork = (NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
if(isConnected) {
switch (activeNetwork.getType()){
case ConnectivityManager.TYPE_WIFI:
postValue(new ConnectionModel(WifiData,true));
break;
case ConnectivityManager.TYPE_MOBILE:
postValue(new ConnectionModel(MobileData,true));
break;
}
} else {
postValue(new ConnectionModel(0,false));
}
}
}
};
}

Now we’ll be notified about any state change, if we’ll observe this LiveData.

So in our activity, we’ll put an observer on the live data in onCreate().

ConnectionLiveData connectionLiveData = new ConnectionLiveData(getApplicationContext());
connectionLiveData.observe(this, new Observer<ConnectionModel>() {
@Override
public void onChanged(@Nullable ConnectionModel connection) {
if (connection.getIsConnected()) {
switch (connection.getType()) {
case WifiData:
Toast.makeText(this, String.format("Wifi turned ON"), Toast.LENGTH_SHORT).show();
break;
case MobileData:
Toast.makeText(this, String.format("Mobile data turned ON"), Toast.LENGTH_SHORT).show();
break;
}
} else {
Toast.makeText(this, String.format("Connection turned OFF"), Toast.LENGTH_SHORT).show();
}
}
});

That’s it. For full code you can check out my gist.

Hope it’ll help you in some way :).

Happy LiveCoding!

The (retired) Pub(lication) for Android & Tech, focused on Development