在 Android NDK 中将标准输出重定向到 logcat [英] Redirect stdout to logcat in Android NDK

查看:28
本文介绍了在 Android NDK 中将标准输出重定向到 logcat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法让我的 Nexus S(运行 Android 4.0)将本机标准输出消息重定向到 logcat.我读过我需要这样做:

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

但是,这似乎不起作用.(它确实破坏了 JUnit,如前所述 这里,所以也不是没有效果.)

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");
  }
}

还有 JNI .c 文件:

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).
");
  fflush(stdout);

  //setvbuf(stderr, NULL, _IONBF, 0);
  //fprintf(stderr, "This message comes from C (JNI).
");
  //fflush(stderr);
}

还有 Android.mk:

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)

我只是通过调用 ndk-build 来编译它.本机方法被正确调用,但我没有从中得到任何日志输出(即使是详细的).我确实从 Java 获得了日志输出(此消息来自 Java.").

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:我已经建立了一个小型 Mercurial 存储库来演示该问题:https://bitbucket.org/skrysmanski/android-ndk-log-output/

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

推荐答案

setprop log.redirect-stdio true 只重定向java代码生成的输出,不重定向本地代码.这个事实是 developer.android.com 描述的方式如下:

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:

默认情况下,Android 系统将 stdout 和 stderr(System.out 和 System.err)输出发送到/dev/null.在运行 Dalvik VM 的进程中,您可以让系统将输出的副本写入日志文件.

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

这篇关于在 Android NDK 中将标准输出重定向到 logcat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆