简体   繁体   English

Android Firebase 检查连接状态?

[英]Android Firebase check connection status?

I have an App with the Firebase Realtime Database.我有一个带有 Firebase 实时数据库的应用程序。 This app should display a ProgressBar if it isn't connected.如果未连接,此应用程序应显示 ProgressBar。 How can I do that?我怎样才能做到这一点? I tried it with ".info/connected", but the results seem pretty random.我用“.info/connected”试过了,但结果似乎很随机。 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 */
  }
});

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 请参阅此链接以获取更多信息

Some nicer check of network connection in kotlin:在 kotlin 中更好地检查网络连接:

val Context.isNetworkConnected
    get() = (getSystemService(ContextWrapper.CONNECTIVITY_SERVICE) as ConnectivityManager)
        .activeNetworkInfo?.isConnected ?: false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM