Зарегистрируйте идентификатор ответа на объявление в Crashlytics.

Выберите платформу: iOS Unity Android (Legacy)

Firebase Crashlytics is a lightweight, realtime crash reporter that makes it easy for you to manage stability issues in your app. Crashlytics saves you troubleshooting time by intelligently grouping crashes and highlighting the circumstances that lead up to them.

This guide describes how to integrate Crashlytics into your Android Studio project so that you can log ad response IDs. Later, when you troubleshoot crashes in your app, you can look up the ad response ID and use the Ad Review Center in AdMob to find and block the ads.

Шаг 1: Добавьте Firebase в Android-приложение

  1. If you would like to try logging with Firebase from a clean app, you can download or clone Google Mobile Ads SDK (Legacy) examples for Android repository on GitHub. This guide specifically uses the Banner Example .

    If you already have an app, you should be able to proceed to other steps with your app's package name. The same steps can also be applied to other examples in the repository with minor adaptations.

  2. Для использования Firebase Crashlytics необходимо создать проект Firebase и добавить в него ваше приложение. Если вы еще этого не сделали, создайте проект Firebase. Обязательно зарегистрируйте в нем свое приложение .

    1. На странице Crashlytics в консоли Firebase нажмите «Настроить Crashlytics» .

    2. На появившемся экране нажмите «Нет» > «Настроить новое приложение Firebase» .

  3. В файл build.gradle добавьте зависимости для Google Analytics, Fabric и Crashlytics.

    app/build.gradle

    apply plugin: 'com.android.application'
    apply plugin: 'com.google.gms.google-services'
    
    // Add the Fabric plugin
    apply plugin: 'io.fabric'
    
    dependencies {
        // ...
    
        // Add Google Mobile Ads SDK (Legacy)
        implementation 'com.google.android.gms:play-services-ads:25.4.0'
    
        // Add the Firebase Crashlytics dependency.
        implementation 'com.google.firebase:firebase-crashlytics:20.1.0'
    }

    проект/build.gradle

    buildscript {
        repositories {
            // ...
            // Add Google's Maven repository.
            google()
        }
    
        dependencies {
            // ...
    
            classpath 'com.google.gms:google-services:4.5.0'
    
            // Add the Fabric Crashlytics plugin.
            classpath 'com.google.firebase:firebase-crashlytics-gradle:3.0.7'
        }
    }
    
    allprojects {
        // ...
        repositories {
           // Check that Google's Maven repository is included (if not, add it).
           google()
    
           // ...
        }
    }
  4. Соберите и запустите приложение, чтобы убедиться в правильной настройке Crashlytics. После успешного завершения вы сможете получить доступ к панели управления Crashlytics.

(Необязательно): Проверьте свою настройку

Добавив кнопку сбоя, вы можете принудительно вызвать сбой приложения при каждом нажатии этой кнопки.

Вот пример, демонстрирующий, как добавить кнопку аварийного завершения в метод onCreate() Activity :

Основная активность (фрагмент)

Java

protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_my);

  // Gets the ad view defined in layout/ad_fragment.xml with ad unit ID set in
  // values/strings.xml.
  adView = findViewById(R.id.ad_view);

  // Start loading the ad in the background.
  adView.loadAd(new AdRequest.Builder().build());

  // Add a crash button.
  Button crashButton = new Button(this);
  crashButton.setText("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));
}

Котлин

override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  setContentView(R.layout.activity_my)

  // Gets the ad view defined in layout/ad_fragment.xml with ad unit ID set in
  // values/strings.xml.
  adView = findViewById(R.id.ad_view)

  // Start loading the ad in the background.
  adView.loadAd(AdRequest.Builder().build())

  // Add a crash button.
  val crashButton = Button(this)
  crashButton.text = "Crash!"
  crashButton.setOnClickListener {
    throw RuntimeException("Test Crash") // Force a crash
  }

  addContentView(crashButton, ViewGroup.LayoutParams(
      ViewGroup.LayoutParams.MATCH_PARENT,
      ViewGroup.LayoutParams.WRAP_CONTENT))
}

In Android Studio, build and run your app on an emulator or a connected device. After the app is loaded, you can click the Crash button. Relaunch the app from the device or Android Studio for the crash log to be uploaded to Crashlyics.

Шаг 2: Зарегистрируйте идентификатор ответа на объявление.

Если вы загружаете несколько объявлений и показываете их в разное время, рекомендуется регистрировать идентификатор ответа на каждое объявление с отдельным ключом. Например, в этом руководстве используется пример только с одним баннерным объявлением. Поэтому в следующем фрагменте кода мы регистрируем идентификатор ответа на объявление как ключ banner_ad_response_id . Действительно, в Firebase Crashlytics можно создать несколько пользовательских пар ключ/значение для разных типов объявлений и событий, связанных с объявлениями (см. AdListener для жизненного цикла объявления). Для получения дополнительной информации о пользовательском логировании посетите раздел «Настройка отчетов о сбоях Firebase Crashlytics» .

Add the following code to your MyActivity.java . Essentially, it uses the FirebaseCrashlytics.setCustomKey() function in the onAdLoaded() callback function to ensure that the ad has loaded before attempting to call getResponseInfo() .

Java

protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_my);

  // Gets the ad view defined in layout/ad_fragment.xml with ad unit ID set in
  // values/strings.xml.
  adView = findViewById(R.id.ad_view);

  adView.setAdListener(new AdListener() {
    @Override
    public void onAdLoaded() {
      String adResponseId = adView.getResponseInfo().getResponseId();
      FirebaseCrashlytics.getInstance().setCustomKey(
          "banner_ad_response_id", adResponseId);
    }
  });

  // Start loading the ad in the background.
  adView.loadAd(new AdRequest.Builder().build());

  // Add a crash button.
  Button crashButton = new Button(this);
  crashButton.setText("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));
}

Котлин

override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  setContentView(R.layout.activity_my)

  // Gets the ad view defined in layout/ad_fragment.xml with ad unit ID set in
  // values/strings.xml.
  adView = findViewById(R.id.ad_view)

  adView.adListener = object : AdListener() {
    override fun onAdLoaded() {
      mAdView.responseInfo?.responseId?.let { adResponseId ->
          FirebaseCrashlytics.getInstance().setCustomKey(
              "banner_ad_response_id", adResponseId)
      }
    }
  }

  // Start loading the ad in the background.
  adView.loadAd(AdRequest.Builder().build())

  // Add a crash button.
  val crashButton = Button(this)
  crashButton.text = "Crash!"
  crashButton.setOnClickListener {
    throw RuntimeException("Test Crash") // Force a crash
  }

  addContentView(crashButton, ViewGroup.LayoutParams(
      ViewGroup.LayoutParams.MATCH_PARENT,
      ViewGroup.LayoutParams.WRAP_CONTENT))
}

Congratulations! You will now see the most recent banner_ad_response_id in the key section of crash sessions on your Crashlytics dashboard. Note that some keys may take up to an hour to become visible in your dashboard.