显示对话框以要求用户在 Firebase Crashlytics 发生崩溃后报告崩溃

Show dialog to ask the user to report a crash after it happened with Firebase Crashlytics

我正在使用 Firebase 的 Crashlytics,崩溃报告已上传到 Crashlytics 控制台。现在我的意图是仅在用户同意的情况下上传崩溃报告。为此,我想向用户显示报告并询问 he/she 是否要发送它。我想对发生的每一次崩溃都这样做。这可能吗?

到目前为止,我只在文档中找到了如何启用选择加入报告

By default, Firebase Crashlytics automatically collects crash reports for all your app's users. To give users more control over the data they send, you can enable opt-in reporting instead.

To do that, you have to disable automatic collection and initialize Crashlytics only for opt-in users.

  1. Turn off automatic collection with a meta-data tag in your AndroidManifest.xml file:
<meta-data android:name="firebase_crashlytics_collection_enabled" android:value="false" />

Enable collection for selected users by initializing Crashlytics from one of your app's activities:

Fabric.with(this, new Crashlytics());

但我希望能够在崩溃发生时捕捉到崩溃,并在应用再次启动时显示包含信息的对话框,并征求用户同意将其上传到 Crashlytics 控制台。

您可以创建自定义 UncaughtExceptionHandler

  1. 在您的 Application class 中,您像往常一样初始化 Crashlytics。
  2. 然后将默认异常处理程序设置为您的自定义处理程序:

    UncaughtExceptionHandler customHandler = 
        new UserAgreementExceptionHandler(Thread.getDefaultUncaughtExceptionHandler());
    Thread.setDefaultUncaughtExceptionHandler(customHandler);
    

在这种情况下,所有未捕获的异常都将传递给您的处理程序。下一个目标是根据您的需要定制它。它看起来像这样:

public class UserAgreementExceptionHandler implements Thread.UncaughtExceptionHandler {

  @NonNull
  private Thread.UncaughtExceptionHandler defaultHandler;

  public UserAgreementExceptionHandler(@NonNull Thread.UncaughtExceptionHandler defaultHandler) {
    this.defaultHandler = defaultHandler;
  }

  @Override
  public void uncaughtException(Thread thread, Throwable ex) {
    // Show dialog to user, pass callbacks for answers inside

    // If user agreed to send the data, 
    // call the default handler you passed on object creation:

    // defaultHandler.uncaughtException(thread, ex);

    // Otherwise, don't pass it further
  }
}

唯一的问题是如何从中启动对话,这取决于您的应用架构。您可以在其中注入一些业务逻辑 class,等待使用现在屏幕上的 Activity Context 显示对话框。