前言
在实际开发中,我们可能会遇到需要在Java应用程序中调用Native方法的情况,为了更好地跟踪代码执行路径,我们可以同时打印Java和Native的堆栈信息。我们希望在出现异常时能够获取到完整的Java和Native堆栈信息,以便更好地定位问题。
1、Native C++层加堆栈打印
1.1、Android版本区分
Andorid O(8.0)以上
Android.mk: LOCAL_SHARED_LIBRARIES里包含libutilscallstack Android.bp: shared_libs里包含libutilscallstack
Android O(8.0)
Android.mk: LOCAL_SHARED_LIBRARIES里包含libutils Android.bp: shared_libs里包含libutils
Android N(7.0) 以前版本
Android.mk: LOCAL_SHARED_LIBRARIES里包含libutils
1.2、基于Android13使用步骤
1.2.1、引用库
cc_defaults {
name: "bootanimation_defaults",
...
shared_libs: [
"libandroidfw",
"libbase",
"libbinder",
"libcutils",
"liblog",
"libutils",
# 库
"libutilscallstack"
],
}
1.2.2、头文件
#include "utils/CallStack.h"
1.2.3、调用代码
android::CallStack cs("zxx");
cs.update();
cs.log("zxx",ANDROID_LOG_ERROR,"");
1.2.4、调用代码在开机画面中BootAnimation打印测试
bool BootAnimation::android() {
android::CallStack cs("zxx");
cs.update();
cs.log("zxx",ANDROID_LOG_ERROR,"");
...
}
2、Java层加堆栈打印
Log.i("zxx","onCreate",new Exception()); 或者Log.i("zxx", Log.getStackTraceString(new Throwable()));
3、AndroidLog打印
在 JNI 中打印日志可以使用 __android_log_print 函数来实现。该函数是 Android NDK 提供的一个用于在本地代码中输出日志消息到 logcat 的方法
3.1、JNI的AndroidLog打印
3.1.1、在你的 JNI C/C++ 代码中包含 <android/log.h> 头文件:
#include <android/log.h>
3.1.2、 __android_log_print 函数来打印日志。它的原型定义如下
__android_log_print(int priority, const char* tag, const char* format, ...)
3.1.3、使用方法定义
#define LOG_TAG "debug"
#define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, fmt, ##args)
#define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, fmt, ##args)
#define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, fmt, ##args)
3.1.4、打印
LOGI("test log!!!!")
3.2、Android.bp的AndroidLog打印
3.2.1、引用库
cc_defaults {
shared_libs: [
"liblog"
],
}
3.2.2、头文件
#include <utils/Log.h>
3.2.3、调用代码
ALOGE("ERROR: could not find class '%s'\n", mClassName.string());