【问题标题】:How to check if firebase service is available?如何检查firebase服务是否可用?
【发布时间】:2016-07-14 12:27:54
【问题描述】:

如果应用在防火墙后运行,或者出现网络中断或某种审查,我们如何使用代码检查应用是否可以访问 Firebase 系统?

【问题讨论】:

  • 如果投反对票的人解释了原因会很有帮助。
  • not the downvoter 您特别希望使用什么 Firebase 功能,因为其中许多人的答案可能不同。
  • @FrankvanPuffelen,我使用了很多(auth、database、fcm、storage)。我的问题是代码不断失败,这可能是由于互联网限制(即它可以与不同的 ISP 一起使用)。这是我看到需要处理的情况。
  • 您可以检查您的应用是否有网络连接。但这并不意味着他们可以访问每个 Firebase 功能。对于数据库,您可以detect the connection state by listening for .info/connected。对于存储,您可以检查已知(小)标记图像等。由于每个服务独立运行,因此每个服务都不同,并且通常无法回答。
  • 谢谢,这很有帮助。

标签: android firebase


【解决方案1】:

您应该像这样检查 Google Play 服务是否可用:

/**
* Check the device to make sure it has the Google Play Services APK. If it
* doesn't, display a dialog that allows users to download the APK from the
* Google Play Store or enable it in the device's system settings.
*/
public static boolean checkPlayServices(Context context) {
    int resultCode = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable
            (context);
    if (resultCode != ConnectionResult.SUCCESS) {
        Log.i(TAG, "This device does not support Google Play Services. " +
                "Push notifications are not supported");
        return false;
    }
    return true;
}

您还需要将以下行添加到您的build.gradle

compile 'com.google.android.gms:play-services-gcm:11.8.0'

【讨论】:

  • 有趣的方法。许多安卓用户不知道谷歌服务并非在全球所有国家都可用。一些国家禁止 google play 服务。有时问题不在于它现在是否可用、已连接、已断开连接……而是它是否可用。这种检查可以帮助确定...
【解决方案2】:

我猜目前您无法通过应用内的代码检查 Firebase 是否可用。但是,您可以通过检查 Firebase 状态仪表板来检查 Firebase 本身是否工作正常。

您还可以在此站点中找到过去 Firebase 服务不可用或不稳定的日期。

希望它在某种程度上有所帮助。

https://status.firebase.google.com/

【讨论】:

    【解决方案3】:

    作为

    FirebaseApp.getInstance() throws IllegalStateException 
    

    你我试试下面的解决方案

    private val isFirebaseEnabled: Boolean
        get() {
            return try {
                FirebaseApp.getInstance() != null.   //that is always true, nevertheless it will throw exception if Firebase is not available
            } catch (e: IllegalStateException) {
                false
            }
        }
    

    不幸的是,它不会检查实际的网络限制。您可以尝试 ping FCM 并捕获连接超时。例如

    private fun isInternetAvailable(): Boolean {
        return try {
            val connection = URL("https://theUrl.com").openConnection() as HttpURLConnection
            connection.setRequestProperty("User-Agent", "Test")
            connection.connectTimeout = 10000
            connection.connect()
            connection.disconnect()
            true
        } catch (e: Exception) {
            false
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-03
      • 1970-01-01
      • 2016-05-19
      相关资源
      最近更新 更多