且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以在没有JNI的情况下直接从本机代码记录Android systrace事件?

更新时间:2023-10-20 16:45:22

我认为它不是从NDK公开的.

I don't think it's exposed from the NDK.

如果您查看来源,则可以看到本地代码即可完成实际工作.该代码调用atrace_begin()atrace_end(),它们在

If you look at the sources, you can see that the android.os.Trace class calls into native code to do the actual work. That code calls atrace_begin() and atrace_end(), which are declared in a header in the cutils library.

如果您从完整的源代码树中提取标头并链接到内部库,则可以直接使用atrace函数.但是,您可以从标题中看到atrace_begin()只是:

You may be able to use the atrace functions directly if you extract the headers from the full source tree and link against the internal libraries. However, you can see from the header that atrace_begin() is simply:

static inline void atrace_begin(uint64_t tag, const char* name)
{
    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
        char buf[ATRACE_MESSAGE_LENGTH];
        size_t len;
        len = snprintf(buf, ATRACE_MESSAGE_LENGTH, "B|%d|%s", getpid(), name);
        write(atrace_marker_fd, buf, len);
    }
}

事件直接写入跟踪文件描述符. (请注意,时间戳记不是事件的一部分;它是自动添加的.)您可以在代码中执行类似的操作;请参阅.c文件中的atrace_init_once() 查看文件的打开方式.

Events are written directly to the trace file descriptor. (Note that the timestamp is not part of the event; that's added automatically.) You could do something similar in your code; see atrace_init_once() in the .c file to see how the file is opened.

请记住,除非atrace作为NDK的一部分发布,否则使用它的任何代码都是不可移植的,并且可能会在Android的过去或将来版本中失败.但是,由于systrace是调试工具,而不是您实际上不希望在应用程序中启用的工具,因此兼容性可能不是问题.

Bear in mind that, unless atrace is published as part of the NDK, any code using it would be non-portable and likely to fail in past or future versions of Android. However, as systrace is a debugging tool and not something you'd actually want to ship enabled in an app, compatibility is probably not a concern.