Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to call C function in Android

Shulou Source: shulou.com Published: 2022-06-02 09:41:39 11月13日 Update

It is believed that many inexperienced people have no idea about how to call the function of C in Android. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Activity_main.xml

The button adds the event name of onCLick to btnclick, and we select to create this button event in the corresponding Activity through Alt+Enter.

MainActivity.java

Let's go back to MainActivity, where the default stringFromJni method is to return a string directly, and then we can take a look at the source code.

Next, let's try how to implement the method with parameters.

We created a new settextgood method with one input parameter and one return parameter.

As you can see, the method just defined is displayed in red font, then we mouse over the method name, then press ALT+ENTER to select the first item in the red box below

The program automatically jumps to the folder of native-lib.cpp and creates the corresponding calling method.

Next, let's write the method of this settextgood

Extern "C" JNIEXPORT jstring JNICALLJava_dem_vac_vaccaendk_MainActivity_settextgood (JNIEnv * env, jobject instance, jstring str_) {const char * str = env- > GetStringUTFChars (str_, 0)

/ / define the appended character char * addstr= ", I am the appended character"; / / define the character to be output and set the length char * outputstr = new char [strlen (str) + strlen (addstr)]; / / start assembling the output character / / 1. The incoming characters are copied into strcpy (outputstr,str); / / 2. Concatenate the additional character strcat (outputstr,addstr) just defined

/ / release resource env- > ReleaseStringUTFChars (str_, str)

Return env- > NewStringUTF (outputstr);}

Finally, we rewrite a button event and click in to pass in a "Hello".

Let's run the program to see

When we first came in, it showed Hello from clocking cards. Now let's click the test button again and see the results.

After reading the above, have you mastered how to call the function of C in Android? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Methods characters buttons next events parameters functions content more programs problems creation testing output selection helpless for this time reason Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Docker Shulou Technology NVidia Xiaomi