我无法让我的 Nexus S(运行 Android 4.0)将 native 标准输出消息重定向到 logcat。我读过我需要这样做:
$ adb shell stop
$ adb shell setprop log.redirect-stdio true
$ adb shell start
但是,这似乎不起作用。 (但它确实破坏了 JUnit,正如提到的 here ,所以它并非没有效果。)
作为引用,这是我的代码:
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");
}
}
还有 JNI .c 文件:
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);
}
还有 Android.mk:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := jni_test
LOCAL_SRC_FILES := test_jni.c
include $(BUILD_SHARED_LIBRARY)
我只是通过调用 ndk-build
来编译它。 native 方法被正确调用,但我没有从中得到任何日志输出(即使是详细的)。我确实从 Java 获得了日志输出(“此消息来自 Java。”)。
任何提示我可能做错了什么?
PS:我已经建立了一个小型 Mercurial 存储库来演示该问题:https://bitbucket.org/skrysmanski/android-ndk-log-output/
最佳答案
setprop log.redirect-stdio true
仅重定向由 java 代码生成的输出,而不是 native 代码。这个事实是described on developer.android.com通过以下方式:
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.
为了从 native 代码中获取输出,我非常喜欢 this solution
关于android - 在 Android NDK 中将标准输出重定向到 logcat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10531050/