1. 导入log头文件
添加logger.h文件,在文件中导入 log.h 头文件
#include<android/log.h>
2. CmakeLists添加库
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log )
# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.
target_link_libraries( # Specifies the target library.
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib} )
3. 定义Log函数
方式一:通过变量开关控制
#include <android/log.h>
#define LOGOPEN 1 //日志开关,1为开,其它为关
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__))
#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))
#if (LOGOPEN == 1)
#define LOG_TAG "JNILearning"
#define LOGV(...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
#define LOGD(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))
#else
#define LOGV(...)
#define LOGD(...)
#define LOGI(...)
#endif
方式二:通过编译宏参数控制
在build.gradle中根据release或者debug添加编译参数,即gcc或者g++里面提到的编译宏
defaultConfig{
buildTypes {
release {
externalNativeBuild {
cmake {
cppFlags " "
cFlags " "
}
}
}
debug{
// 添加编译宏,在C 或者 C++源码中添加 LOG_DEBUG 的编译宏
externalNativeBuild {
cmake {
cppFlags "-DLOG_DEBUG"
cFlags "-DLOG_DEBUG"
}
}
}
}
}
#include <android/log.h>
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__))
#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))
#ifdef LOG_DEBUG
#define LOG_TAG "JNILearning"
#define LOGV(...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
#define LOGD(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))
#else
#define LOGV(...)
#define LOGD(...)
#define LOGI(...)
#endif
使用示例
extern "C" JNIEXPORT jstring JNICALL
Java_com_gavinchoo_jni_learning_LearningJni_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
std::string hello = "Hello from C++";
LOGD("%s", hello.c_str());
return env->NewStringUTF(hello.c_str());
}