2012-04-23 63 views
35

如果我在Java文件中定義這樣的功能如何獲得用NDK應用程序編寫的「printf」消息?

/** 
    * Adds two integers, returning their sum 
    */ 
    public native int add(int v1, int v2); 

,所以我需要在C文件編寫

JNIEXPORT jint JNICALL Java_com_marakana_NativeLib_add 
    (JNIEnv * env, jobject obj, jint value1, jint value2) { 

    printf("\n this is log messge \n"); 

     return (value1 + value2); 
} 

然後從這個地方的printf將打印信息? 在logcate我沒有得到它?

如何通過放置日誌消息來調試任何NDK應用程序?

+1

'printf(3)'將寫入任何_standard output_ - 可能或可能不存在於您的環境中。更好的辦法是找到一個支持的日誌記錄機制。 – sarnold 2012-04-23 04:52:52

回答

83

改爲使用__android_log_print()。您必須包含標題<android/log.h>

示例示例。 __android_log_print(ANDROID_LOG_DEBUG, "LOG_TAG", "\n this is log messge \n");

您也可以使用格式說明如printf -

__android_log_print(ANDROID_LOG_DEBUG, "LOG_TAG", "Need to print : %d %s",int_var, str_var); 

請確保您還鏈接對日誌庫,在你的Android.mk文件:

LOCAL_LDLIBS := -llog 

喔..忘了。 。輸出將顯示在Logcat帶標籤LOG_TAG

簡易方法

將以下行添加到您的公共頭文件中。

#include <android/log.h> 

#define LOG_TAG "your-log-tag" 

#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) 
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) 
// If you want you can add other log definition for info, warning etc 

現在只需撥打LOGD("Hello world") or LOGE("Number = %d", any_int)printf in c

不要忘記包含公共頭文件。

刪除日誌

如果定義LOGD(...)空,所有的日誌將會消失。只需在LOGD(...)之後發表評論。

#define LOGD(...) // __android_log..... rest of the code

+0

如何刪除日誌記錄? – powder366 2013-11-29 18:00:34

+1

@ powder366答案已更新。檢查刪除記錄部分。 – Shaiful 2013-12-03 09:55:43

+5

爲了防止有人(例如我)使用Android Studio(當前版本爲0.8.11),您將ldLibs「log」放在「ndk」標籤內。 這解決了對'__android_log_print'問題的未定義引用。 – Yang 2014-10-05 07:49:48

12

有兩種選擇:

1)__android_log_print更換的printf。您可以在代碼開頭很容易地確定這樣做:

#define printf(...) __android_log_print(ANDROID_LOG_DEBUG, "TAG", __VA_ARGS__); 

當然這需要改變有printf的所有源代碼。

2)重定向輸出和錯誤到Android logcat的(不知道這是否會在非root權限的設備工作):http://developer.android.com/guide/developing/debugging/debugging-log.html#viewingStd

+0

當我使用選項2,然後在運行我的應用程序模擬器時應用那3命令只是掛斷顯示android bootanimation .. – 2012-04-23 06:11:07

5

不需要根設備,acroding到http://developer.android.com/guide/developing/debugging/debugging-log.html#viewingStd,下面可以prefectly工作。

$ adb shell 

$ su 

$ stop 

$ setprop log.redirect-stdio true 

$ start 

完成!

+2

蘇命令將無法工作沒有root訪問.. !!無論如何, – 2014-06-20 03:02:52

+0

+1用於指出setprop方法。 – 2014-06-20 05:08:33

+2

此方法僅適用於運行dalvik(4.4或更早版本)的Android版本,ART版本(5.0或更高版本)不支持log.redirect-stdio。資料來源:https://code.google.com/p/android/issues/detail?id=165602 – Deemoe 2016-03-22 21:01:16

相關問題