Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect stdout to logcat in Android NDK

I can't get my Nexus S (running Android 4.0) to redirect native stdout message to logcat. I've read that I need to do this:

$ adb shell stop $ adb shell setprop log.redirect-stdio true $ adb shell start 

However, this doesn't seem to work. (It does break JUnit though, as mentioned here, so it's not without effect.)

For reference, here's my code:

package com.mayastudios;  import android.util.Log;  public class JniTester {    public static void test() {     Log.e("---------", "Start of test");     System.err.println("This message comes from Java.");         void printCMessage();     Log.e("---------", "End of test");   }    private static native int printCMessage();    static {     System.loadLibrary("jni_test");   } } 

And the JNI .c file:

JNIEXPORT void JNICALL Java_com_mayastudios_JniTester_printCMessage(JNIEnv *env, jclass cls) {   setvbuf(stdout, NULL, _IONBF, 0);   printf("This message comes from C (JNI).\n");   fflush(stdout);    //setvbuf(stderr, NULL, _IONBF, 0);   //fprintf(stderr, "This message comes from C (JNI).\n");   //fflush(stderr); } 

And the Android.mk:

LOCAL_PATH := $(call my-dir)  include $(CLEAR_VARS) LOCAL_MODULE    := jni_test LOCAL_SRC_FILES := test_jni.c include $(BUILD_SHARED_LIBRARY) 

I'm compiling this just by calling ndk-build. The native method is called correctly but I don't get any log output from it (even on verbose). I do get the log output from Java though ("This message comes from Java.").

Any hints of what I might be doing wrong?

PS: I've set up a small Mercurial repository that demonstrates the problem: https://bitbucket.org/skrysmanski/android-ndk-log-output/

like image 577
Sebastian Krysmanski Avatar asked May 10 '12 09:05

Sebastian Krysmanski


2 Answers

setprop log.redirect-stdio true redirects only output generated by java code, but not the native code. This fact is described on developer.android.com in following way:

By default, the Android system sends stdout and stderr (System.out and System.err) output to /dev/null. In processes that run the Dalvik VM, you can have the system write a copy of the output to the log file.

To get output from the native code, I really liked this solution

like image 69
sqr163 Avatar answered Sep 20 '22 02:09

sqr163


This was not obvious to me from the previous answers. Even on rooted devices you need to run:

adb root adb shell stop adb shell setprop log.redirect-stdio true adb shell start 
like image 45
user2802811 Avatar answered Sep 21 '22 02:09

user2802811