Android JNI中是有提供相关的接口来记录log的,这样的话,和java写的代码一样,可以直接在logcat中查看。如果代码里都是android提供的log api,一旦遇到新的需求,改起来会很麻烦,每个地方都需要修改,所以说封装android提供的log api是很有必要的。
====
android提供的常用api
__android_log_write(ANDROID_LOG_INFO, "tag here", "message here");
__android_log_print(ANDROID_LOG_INFO, "sometag", "test int = %d", testInt);
====
如何使用?
1. 包含头文件
#include <android/log.h>
2. 链接相关的库文件
android.mk需要加上引入库
LOCAL_LDLIBS += -L$(SYSROOT)/usr/lib -llog
====
封装
#include <stdio.h>
#include <stdarg.h>
#include <android/log.h>
#include <time.h>
static const char* TAG = "uninstall";
void kesyPrintf(const char *format, ...)
{
#ifdef KE_DEBUG
char buf[2048] = "\0";
va_list args;
va_start(args,format);
vsprintf(buf + strlen(buf), format, args);
va_end(args);
// 可以添加功能,在这里可以把log记录在文件中
// -----
__android_log_write(ANDROID_LOG_INFO, TAG, buf);
#endif
}
. KE_DEBUG是一个宏定义,作为一个开关,只有定义了KE_DEBUG,才会输出log。可以在代码中定义,也可以在mk文件中定义。
. 这样就可以像C语言中的printf那样打印log了
kesyPrint("Hello world\n");
kesyPrint("abc---%s", "efg");
-------------------欢迎评头品足-----by jacksonke