Android Firebase check connection status?

Issue

I have an App with the Firebase Realtime Database. This app should display a ProgressBar if it isn’t connected. How can I do that? I tried it with “.info/connected”, but the results seem pretty random. I need to check the connection to the online database, not the offline database. (basically, i want to disable offline capabilities, and show the user if they are offline)

Solution

var firebaseRef = new Firebase('http://INSTANCE.firebaseio.com');
firebaseRef.child('.info/connected').on('value', function(connectedSnap) {
  if (connectedSnap.val() === true) 
  {
    /* we're connected! */
  } 
  else {
    /* Give a custom Toast / Alert dialogue and exit the application */
  }
});

You can also add this check

public static boolean isNetworkAvailable(Context con) {
        try {
            ConnectivityManager cm = (ConnectivityManager) con
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();

            if (networkInfo != null && networkInfo.isConnected()) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

Then check this in your Activity/Fragment

if (isNetworkAvailable)
{
//Do you task
}
else{
/*No internet so  Give a custom Toast / Alert dialogue and exit the application */
}

Refer this link for more information

Answered By – Akshay Katariya

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published