gpt4 book ai didi

android - LeakCanary有回调吗?

转载 作者:行者123 更新时间:2023-11-29 18:37:24 26 4
gpt4 key购买 nike

如何获取 LeakCanary 日志或有关泄漏的任何类型的数据?LeakCanary 是否有任何类型的回调,我们可以使用它来获取“泄漏数据”以在它发生时对其进行处理?我想将数据发送到我的 FireBase 或其他一些数据库。

我在文档中进行了搜索,但没有找到相关信息。

感谢大家

最佳答案

TLDR;你需要扩展 DisplayLeakService

https://github.com/square/leakcanary/wiki/Customizing-LeakCanary#uploading-to-a-server

您可以更改默认行为以将泄漏跟踪和堆转储上传到您选择的服务器。

创建您自己的 AbstractAnalysisResultService。最简单的方法是在调试源中扩展 DisplayLeakService:

public class LeakUploadService extends DisplayLeakService {
@Override protected void afterDefaultHandling(HeapDump heapDump, AnalysisResult result, String leakInfo) {
if (!result.leakFound || result.excludedLeak) {
return;
}
if (result.leakFound) {
uploadLeakToServer(result, leakInfo);
}
}

private void uploadLeakToServer(AnalysisResult result, String leakInfo) {
// TODO Upload result to server
}
}

您可以使用 AnalysisResult.leakTraceAsFakeException() 将泄漏跟踪转换为虚假异常,并将它们上传到崩溃报告后端。以下是使用 Bugsnag 的方法:

public class LeakUploadService extends DisplayLeakService {

@Override protected void afterDefaultHandling(HeapDump heapDump, AnalysisResult result, String leakInfo) {
if (!result.leakFound || result.excludedLeak) {
return;
}
if (result.leakFound) {
uploadLeakToServer(result, leakInfo);
}
}

private void uploadLeakToServer(AnalysisResult result, String leakInfo) {
Client bugsnagClient = new Client(getApplication(), "YOUR_BUGSNAG_API_KEY", false);
bugsnagClient.setSendThreads(false);
bugsnagClient.beforeNotify(error -> {
// Bugsnag does smart grouping of exceptions, which we don't want for leak traces.
// So instead we rely on the SHA-1 of the stacktrace, which has a low risk of collision.
String stackTraceString = Logs.getStackTraceString(error.getException());
String uniqueHash = Strings.createSHA1Hash(stackTraceString);
error.setGroupingHash(uniqueHash);
return true;
});

MetaData metadata = new MetaData();
metadata.addToTab("LeakInfo", "LeakInfo", leakInfo);
bugsnagClient.notifyBlocking(result.leakTraceAsFakeException(), Severity.ERROR, metadata);
}
}

接下来需要在LeakCanary中指定监听服务类:

public class DebugExampleApplication extends ExampleApplication {
@Override protected void installLeakCanary() {
RefWatcher refWatcher = LeakCanary.refWatcher(this)
.listenerServiceClass(LeakUploadService.class);
.buildAndInstall();
}
}

不要忘记在调试 AndroidManifest.xml 中注册服务:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
>
<application android:name="com.example.DebugExampleApplication">
<service android:name="com.example.LeakUploadService" />
</application>
</manifest>

关于android - LeakCanary有回调吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53764804/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com