In our app, we would like the ability to continually check for connectivity status, and if it goes down, throw a Toast or some kind of UI to indicate to the user that it's down. I tried doing this in our Retrofit Api-Builder class whenever API calls are made, but it doesn't seem to like Toasts there (causes crashes).
iOS has a monitoring capability, but it seems on Android, we have to check manually. Is there a simple/clean way of doing this across our app, given there are multiple Activities, etc?
This is how I did to monitor the internet connection status. Create a Java class and name it as NetworkStateChangeReceiver
.
NetworkStateChangeReceiver
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import static android.content.Context.CONNECTIVITY_SERVICE;
public class NetworkStateChangeReceiver extends BroadcastReceiver {
public static final String NETWORK_AVAILABLE_ACTION = "yourapp.packagename.NetworkAvailable";
public static final String IS_NETWORK_AVAILABLE = "isNetworkAvailable";
@Override
public void onReceive(Context context, Intent intent) {
Intent networkStateIntent = new Intent(NETWORK_AVAILABLE_ACTION);
networkStateIntent.putExtra(IS_NETWORK_AVAILABLE, isConnectedToInternet(context));
LocalBroadcastManager.getInstance(context).sendBroadcast(networkStateIntent);
}
private boolean isConnectedToInternet(Context context) {
try {
if (context != null) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
return false;
} catch (Exception e) {
Log.e(NetworkStateChangeReceiver.class.getName(), e.getMessage());
return false;
}
}
}
In your MainActivity, add the following lines.
IntentFilter intentFilter = new
IntentFilter(NetworkStateChangeReceiver.NETWORK_AVAILABLE_ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(new
BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false);
String networkStatus = isNetworkAvailable ? "Connected!" : "Disconnected!";
final SweetAlertDialog CC = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.WARNING_TYPE);
CC.setTitleText("Network Status");
CC.setContentText(networkStatus);
CC.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
CC.setCancelable(false);
CC.show();
You could use a simple alertdialog or a toast to show the message. I had used the SweetAlertDialog Library for cleaner UI.