Ian Rehwinkel
Ian Rehwinkel

Reputation: 2615

Android Firebase check connection status?

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)

Upvotes: 2

Views: 10831

Answers (1)

Akshay Katariya
Akshay Katariya

Reputation: 1474

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

Upvotes: 6

Related Questions