Android Firebase检查连接状态? [英] Android Firebase check connection status?

查看:98
本文介绍了Android Firebase检查连接状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有Firebase实时数据库的应用程序.如果未连接,此应用程序应显示一个ProgressBar.我怎样才能做到这一点?我使用".info/connected"进行了尝试,但是结果似乎是随机的.我需要检查与在线数据库的连接,而不是离线数据库的连接. (基本上,我想禁用离线功能,并向用户显示离线状态)

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)

推荐答案

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 */
  }
});

您也可以添加此支票

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 */
}

请参阅链接以获取更多信息

这篇关于Android Firebase检查连接状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆