Posted on Leave a comment

Connection Detection Using LiveData — Android

https://android.jlelse.eu/connection-detection-using-livedata-android-623bd02b0e30

[code language=”java”]
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;
}
}
[/code]

[code language=”java”]
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));
}
}
}
};
}
[/code]

[code language=”java”]
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();
}
}
});
[/code]

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.