Android集成Sentry

Sentry Android SDK构建于主Java SDK之上,支持所有相同的功能,配置选项等。将Android SDK的1.7.10版本添加到甚至不使用Proguard的示例应用程序中,仅将发布的.apk大小增加了大约200KB。

默认情况下,事件将缓冲到磁盘(在应用程序的缓存目录中)。如果设备在创建事件时没有连接,则允许稍后发送事件。可以通过将选项buffer.enabled设置为false来禁用此功能。

配置UncaughtExceptionHandler,以便将崩溃事件存储到磁盘并在下次运行应用程序时发送。

AndroidEventBuilderHelper默认启用,它将自动使用有关设备当前状态的数据来丰富事件,例如内存使用情况,存储使用情况,显示分辨率,连接性,电池电量,型号,Android版本,设备是否已植根等

一、安装

在app / build.gradle中使用Gradle(Android Studio)添加:

compile 'io.sentry:sentry-android:1.7.10'

// this dependency is not required if you are already using your own
// slf4j implementation
compile 'org.slf4j:slf4j-nop:1.7.25'

对于其他依赖管理器,请查看中央Maven存储库。

二、初始化

您的应用程序必须具有访问Internet的权限才能将事件发送到Sentry服务器。在AndroidManifest.xml中:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 然后在应用程序的main onCreate方法中初始化Sentry客户端:

import io.sentry.Sentry;
import io.sentry.android.AndroidSentryClientFactory;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Context ctx = this.getApplicationContext();

        // Use the Sentry DSN (client key) from the Project Settings page on Sentry
        String sentryDsn = "https://publicKey:secretKey@host:port/1?options";
        Sentry.init(sentryDsn, new AndroidSentryClientFactory(ctx));

        // Alternatively, if you configured your DSN in a `sentry.properties`
        // file (see the configuration documentation).
        Sentry.init(new AndroidSentryClientFactory(ctx));
    }
}

您可以选择配置其他值,例如环境和发布。有关执行此操作的方法,请参阅配置页。

三、事例

现在,您可以使用Sentry捕获应用程序中的任何位置的事件:

import io.sentry.context.Context;
import io.sentry.event.BreadcrumbBuilder;
import io.sentry.event.UserBuilder;

public class MyClass {
    /**
      * An example method that throws an exception.
      */
    void unsafeMethod() {
        throw new UnsupportedOperationException("You shouldn't call this!");
    }

    /**
      * Note that the ``Sentry.init`` method must be called before the static API
      * is used, otherwise a ``NullPointerException`` will be thrown.
      */
    void logWithStaticAPI() {
        /*
         Record a breadcrumb in the current context which will be sent
         with the next event(s). By default the last 100 breadcrumbs are kept.
         */
        Sentry.getContext().recordBreadcrumb(
            new BreadcrumbBuilder().setMessage("User made an action").build()
        );

        // Set the user in the current context.
        Sentry.getContext().setUser(
            new UserBuilder().setEmail("hello@sentry.io").build()
        );

        /*
         This sends a simple event to Sentry using the statically stored instance
         that was created in the ``main`` method.
         */
        Sentry.capture("This is a test");

        try {
            unsafeMethod();
        } catch (Exception e) {
            // This sends an exception event to Sentry using the statically stored instance
            // that was created in the ``main`` method.
            Sentry.capture(e);
        }
    }
}

 四、ProGuard

为了将ProGuard与Sentry一起使用,您需要使用我们的Gradle集成(推荐)或使用sentry-cli手动将proguard映射文件上传到Sentry。

五、Gradle集成

在app / build.gradle中使用Gradle(Android Studio)添加:

apply plugin: 'io.sentry.android.gradle'

并在你的toplevel build.gradle中声明一个依赖:

buildscript {
    dependencies {
        classpath 'io.sentry:sentry-android-gradle-plugin:1.7.10'
    }
}

 然后,插件将自动生成相应的ProGuard映射文件,并在运行gradle assembleRelease时上载它们。上载步骤的凭据是从项目根目录中的sentry.properties文件或通过环境变量加载的,有关更多信息,请参阅sentry-cli文档。至少你需要这样的东西:

defaults.project=your-project
defaults.org=your-org
auth.token=YOUR_AUTH_TOKEN

您可以在Sentry API页面上找到您的身份验证令牌。有关可用配置选项的更多信息,请参阅Sentry配置相关文章。

六、Gradle配置

另外,我们直接在Gradle中公开了一些配置值:

sentry {
    // Disables or enables the automatic configuration of proguard
    // for Sentry.  This injects a default config for proguard so
    // you don't need to do it manually.
    autoProguardConfig true

    // Enables or disables the automatic upload of mapping files
    // during a build.  If you disable this you'll need to manually
    // upload the mapping files with sentry-cli when you do a release.
    autoUpload true
}

七、手动整合

如果您选择不使用Gradle集成,则可以手动处理处理和上载步骤。但是,强烈建议您尽可能使用Gradle集成。

首先,您需要将以下内容添加到ProGuard规则文件中:

-keepattributes LineNumberTable,SourceFile
-dontwarn org.slf4j.**
-dontwarn javax.**
-keep class io.sentry.event.Event { *; }

 八、ProGuard UUIDs

生成ProGuard文件后,您需要将ProGuard映射文件的UUID嵌入assets文件夹中名为sentry-debug-meta.properties的属性文件中。 Java SDK将在那里查找UUID,以将事件链接到服务器端的正确映射文件。

sentry-cli可以为您编写sentry-debug-meta.properties文件:

sentry-cli upload-proguard \
    --android-manifest app/build/intermediates/manifests/full/release/AndroidManifest.xml \
    --write-properties app/build/intermediates/assets/release/sentry-debug-meta.properties \
    --no-upload \
    app/build/outputs/mapping/release/mapping.txt

请注意,此文件需要在您的APK中,因此需要在打包APK之前运行。您可以通过创建在dex打包之前运行的gradle任务来实现。

例如,您可以在proguard步骤之后和执行sentry-cli的dex之前添加gradle任务,以验证和处理映射文件并将UUID写入属性文件:

gradle.projectsEvaluated {
    android.applicationVariants.each { variant ->
        def variantName = variant.name.capitalize();
        def proguardTask = project.tasks.findByName(
            "transformClassesAndResourcesWithProguardFor${variantName}")
        def dexTask = project.tasks.findByName(
            "transformClassesWithDexFor${variantName}")
        def task = project.tasks.create(
                name: "processSentryProguardFor${variantName}",
                type: Exec) {
            workingDir project.rootDir
            commandLine *[
                "sentry-cli",
                "upload-proguard",
                "--write-properties",
                "${project.rootDir.toPath()}/app/build/intermediates/assets" +
                    "/${variant.dirName}/sentry-debug-meta.properties",
                variant.getMappingFile(),
                "--no-upload"
            ]
        }
        dexTask.dependsOn task
        task.dependsOn proguardTask
    }
}

 或者,您可以自己生成UUID,然后强制Sentry在上传后兑现该UUID。但是强烈建议不要这样做!

九、上传ProGuard文件

最后,您需要手动上传带有sentry-cli的ProGuard文件,如下所示:

sentry-cli upload-proguard \
    --android-manifest app/build/intermediates/manifests/full/release/AndroidManifest.xml \
    app/build/outputs/mapping/release/mapping.txt
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值