前言
在實際開發中,我們可能會遇到需要在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());