How to enable / disable own log-cat in ndk at runtime

I use this snippet code to enable or disable the log

   #define DEBUG 1

   #if DEBUG
   #include <android/log.h>
   #define  LOG_TAG    "native_log"
   #define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
   #else
   #  define  LOGD(...)  do {} while (0) // do nothing
   #endif

   // use it
   LOGD("%s : %d","value", val);

It worked fine by turning on / off the flag DEBUG. The problem is that I want to do this at runtime in the java side. What I want like this:

   // java 
   private native void nativeSetDebug(boolean flag);

   // jni
   JNIEXPORT void JNICALL Java_com_my_package_Native_nativeSetDebug(JNIEnv *env, jobject thiz, jboolean flag){
        // what should I do in this method?
   }

Since macros in C ++ are replaced by the preprocessor by their value before the source file is even compiled, so I'm looking for a different approach. Any ideas?

+3
source share
1 answer

macro file

extern bool useDebug;
#include <android/log.h>
#define  LOG_TAG    "native_log"
#define  LOGD(...)  if(useDebug){__android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)}

C file

bool useDebug = true;
JNIEXPORT void JNICALL Java_com_my_package_Native_nativeSetDebug(JNIEnv *env, jobject thiz, jboolean flag){
    useDebug = flag;

}

External is important, otherwise each file, including the header, will define its own variable, and they will not be set correctly.

+5
source

All Articles