Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print onto android screen from native code in NDK?

I wish to print the output from printf statements in my native code(in C) on to android screen. As I have many outputs that I wish to see on android screen, I want something more than the return statements at the end of a JNI functions which print a single text per function. How to go about it?

EDIT:

For example in my C code, if I wish to print something in the middle of a function like "Hello World" what should I do? Right now, I am able to print "only from return!" on the android screen using setText methods.

jstring Java_com_example_encryptString( JNIEnv* env, jobject thiz) 
{
   printf("Hello World");
   return (*env)->NewStringUTF(env, "only from return!");
}

I know of a method where I call this method from the Java class and use TextViews to print it on android screen. But, that can take and print only the value returned by the function and nothing else. Can't I print any other value which is not returned by the function?

Thanks.

Note: I am not looking for android logs in logcat.

like image 930
re3el Avatar asked Sep 27 '22 06:09

re3el


1 Answers

If I understood your question correctly, you meant to set text in a TextView from c code, right?

If so, you can do that. You need to pass the TextView as a param to your native method. Then in your native code call find its setText method and call it.

You can read more on this thread on SO or this page.

You will change your native method to something like this :

jstring Java_com_example_encryptString( JNIEnv* env, jobject thiz, jobject jtextViewObject, ...)
{
    //getting set text method
    jclass clazz = (*env)->FindClass(env, "android/widget/TextView");
    jmethodID setText = (*env)->GetMethodID(env, clazz, "setText", "(Ljava/lang/CharSequence;)V");

    ... do stuff ...

    //set text to text view
    jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
    (*env)->CallVoidMethod(env, jtextViewObject, setText, jstr);

    ... do stuff ...

    return (*env)->NewStringUTF(env, "only from return!");
}

You will also need to change the signature of the native method in java code to add the TextView in the params.

like image 126
sonic Avatar answered Oct 03 '22 14:10

sonic