Начните работу с Firebase Crashlytics


В этом кратком руководстве описывается, как настроить Firebase Crashlytics в вашем приложении с помощью Firebase Crashlytics SDK, чтобы вы могли получать подробные отчеты о сбоях в консоли Firebase .С помощью Crashlytics для Android вы получаете отчеты о сбоях, нефатальных ошибках и ошибках «Приложение не отвечает» (ANR).

Для настройки Crashlytics необходимо выполнить ряд действий как в консоли Firebase , так и в вашей IDE (например, добавить файл конфигурации Firebase и Crashlytics SDK). Для завершения настройки необходимо принудительно вызвать тестовый сбой, чтобы отправить первый отчёт о сбое в Firebase.

Прежде чем начать

  1. Добавьте Firebase в свой проект Android, если вы ещё этого не сделали. Если у вас нет приложения для Android, вы можете скачать пример приложения .

  2. Рекомендуется : для автоматического получения журналов хлебных крошек для понимания действий пользователя, приводящих к сбою, нефатальному событию или событию ANR, вам необходимо включить Google Analytics в вашем проекте Firebase.

    • Если в вашем существующем проекте Firebase не включен Google Analytics , вы можете включить Google Analytics на вкладке «Интеграции» вашего проекта. > Настройки проекта в консоли Firebase .

    • Если вы создаете новый проект Firebase, включите Google Analytics во время процесса создания проекта.

  3. Убедитесь, что ваше приложение имеет следующие минимальные требуемые версии:

    • Gradle 8.0
    • Плагин Android Gradle 8.1.0
    • Плагин Gradle для сервисов Google 4.4.1

Шаг 1 : Добавьте Crashlytics SDK в свое приложение

В файле Gradle вашего модуля (уровня приложения) (обычно <project>/<app-module>/build.gradle.kts или <project>/<app-module>/build.gradle ) добавьте зависимость для библиотеки Crashlytics NDK для Android. Для управления версиями библиотеки мы рекомендуем использовать Firebase Android BoM .

Чтобы воспользоваться журналами навигации , добавьте в приложение Firebase SDK для Google Analytics . Убедитесь, что Google Analytics включен в вашем проекте Firebase.

dependencies {
    // Import the BoM for the Firebase platform
    implementation(platform("com.google.firebase:firebase-bom:34.4.0"))

    // Add the dependencies for the Crashlytics NDK and Analytics libraries
    // When using the BoM, you don't specify versions in Firebase library dependencies
    implementation("com.google.firebase:firebase-crashlytics-ndk")
    implementation("com.google.firebase:firebase-analytics")
}

Используя Firebase Android BoM , ваше приложение всегда будет использовать совместимые версии библиотек Firebase Android.

(Альтернатива) Добавьте зависимости библиотеки Firebase без использования BoM

Если вы решите не использовать Firebase BoM , вам необходимо указать каждую версию библиотеки Firebase в строке ее зависимостей.

Обратите внимание: если вы используете в своем приложении несколько библиотек Firebase, мы настоятельно рекомендуем использовать BoM для управления версиями библиотек, что гарантирует совместимость всех версий.

dependencies {
    // Add the dependencies for the Crashlytics NDK and Analytics libraries
    // When NOT using the BoM, you must specify versions in Firebase library dependencies
    implementation("com.google.firebase:firebase-crashlytics-ndk:20.0.3")
    implementation("com.google.firebase:firebase-analytics:23.0.0")
}

Шаг 2 : Добавьте плагин Crashlytics Gradle в свое приложение.

  1. В корневом файле Gradle (уровня проекта) ( <project>/build.gradle.kts или <project>/build.gradle ) добавьте плагин Crashlytics Gradle в блок plugins :

    Kotlin

    plugins {
        // Make sure that you have the AGP plugin 8.1+ dependency
        id("com.android.application") version "8.1.4" apply false
        // ...
    
        // Make sure that you have the Google services Gradle plugin 4.4.1+ dependency
        id("com.google.gms.google-services") version "4.4.4" apply false
    
        // Add the dependency for the Crashlytics Gradle plugin
        id("com.google.firebase.crashlytics") version "3.0.6" apply false
    }

    Groovy

    plugins {
        // Make sure that you have the AGP plugin 8.1+ dependency
        id 'com.android.application' version '8.1.4' apply false
        // ...
    
        // Make sure that you have the Google services Gradle plugin 4.4.1+ dependency
        id 'com.google.gms.google-services' version '4.4.4' apply false
    
        // Add the dependency for the Crashlytics Gradle plugin
        id 'com.google.firebase.crashlytics' version '3.0.6' apply false
    }
  2. В файле Gradle вашего модуля (уровня приложения) (обычно <project>/<app-module>/build.gradle.kts или <project>/<app-module>/build.gradle ) добавьте плагин Crashlytics Gradle:

    Kotlin

    plugins {
      id("com.android.application")
      // ...
    
      // Make sure that you have the Google services Gradle plugin
      id("com.google.gms.google-services")
    
      // Add the Crashlytics Gradle plugin
      id("com.google.firebase.crashlytics")
    }

    Groovy

    plugins {
      id 'com.android.application'
      // ...
    
      // Make sure that you have the Google services Gradle plugin
      id 'com.google.gms.google-services'
    
      // Add the Crashlytics Gradle plugin
      id 'com.google.firebase.crashlytics'
    }

Step 3 : Force a test crash to finish setup

To finish setting up Crashlytics and see initial data in the Crashlytics dashboard of the Firebase console, you need to force a test crash.

  1. Add code to your app that you can use to force a test crash.

    You can use the following code in your app's MainActivity to add a button to your app that, when pressed, causes a crash. The button is labeled "Test Crash".

    Kotlin

    val crashButton = Button(this)
    crashButton.text = "Test Crash"
    crashButton.setOnClickListener {
       throw RuntimeException("Test Crash") // Force a crash
    }
    
    addContentView(crashButton, ViewGroup.LayoutParams(
           ViewGroup.LayoutParams.MATCH_PARENT,
           ViewGroup.LayoutParams.WRAP_CONTENT))

    Java

    Button crashButton = new Button(this);
    crashButton.setText("Test Crash");
    crashButton.setOnClickListener(new View.OnClickListener() {
       public void onClick(View view) {
           throw new RuntimeException("Test Crash"); // Force a crash
       }
    });
    
    addContentView(crashButton, new ViewGroup.LayoutParams(
           ViewGroup.LayoutParams.MATCH_PARENT,
           ViewGroup.LayoutParams.WRAP_CONTENT));
  2. Build and run your app.

  3. Force the test crash in order to send your app's first crash report:

    1. Open your app from your test device or emulator.

    2. In your app, press the "Test Crash" button that you added using the code above.

    3. After your app crashes, restart it so that your app can send the crash report to Firebase.

  4. Go to the Crashlytics dashboard of the Firebase console to see your test crash.

    If you've refreshed the console and you're still not seeing the test crash after five minutes, enable debug logging to see if your app is sending crash reports.


And that's it! Crashlytics is now monitoring your app for crashes, non-fatal errors, and ANRs. Visit the Crashlytics dashboard to view and investigate all your reports and statistics.

Следующие шаги

  • Integrate with Google Play so that you can filter your Android app's crash reports by Google Play track directly in the Crashlytics dashboard. This allows you to better focus your dashboard on specific builds.
  • In Android Studio, view and filter Crashlytics data.
    • Use the App Quality Insights (AQI) window in Android Studio to view Crashlytics data alongside your code — no need to jump back and forth between the Crashlytics dashboard and the IDE to start debugging top issues.
    • Learn how to use the AQI window in the Android Studio documentation.
    • We'd love to hear from you! Send us feedback about the AQI window by filing a bug report .