Android JNI Programming Demo with Eclipse

Source: Internet
Author: User

Use Eclipse to create a JNI case that shows how to adjust the CPP function in JAVA.

We're going to create a case called Jnidemo, where the main activity will adjust the function of a getversion () called Libhello.so's CPP function to write its return string to the TextView of the main activity.


Start with eclipse to build a new Android Activity case. All other options are available with a preset value.

1. Slightly modify the main activity configuration layout/activity_main.xml, add the ID named title in TextView (Line 12) for later reference

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:paddingbottom= "@dimen/activity_vertical_margin"    android:paddingleft= "@dimen/activity_ Horizontal_margin "    android:paddingright=" @dimen/activity_horizontal_margin "    android:paddingtop=" @dimen /activity_vertical_margin "    tools:context=". Mainactivity ">    <textview        android:id=" @+id/title "        android:layout_width=" Wrap_content        " android:layout_height= "Wrap_content"        android:text= "@string/hello_world"/></relativelayout>



2. Add a Mainactivity.java to the load library and add a native function called GetVersion.

The changes are as follows:

Package Com.example.jnidemo;import Android.os.bundle;import Android.app.activity;import Android.widget.TextView; public class Mainactivity extends Activity {static {system.loadlibrary ("Hello");//Hello.dll (Windows) or libhello.so (Un ixes)}private native String getversion (), @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main); TextView TV = (TextView) Findviewbyid (r.id.title); Tv.settext (GetVersion ()); }}

3. Add a JNI recording. Add a file named HelloJni.cpp under JNI.

/jni/hellojni.cpp content is as follows

#include <jni.h> #include <stdio.h> #define JNIREG_CLASS "com/example/jnidemo/mainactivity"//   Specifies the class to register extern "C" Jniexport jstring jnicall native_getversion (jnienv *env, Jobject thisobj) {jstring szret;   Szret = Env->newstringutf ("V1.0"); return Szret;} /**********************************************************************************/static JNINativeMethod Gmethods[] = {{"GetVersion", "() ljava/lang/string;", (void*) native_getversion},};/** Register several native methods fo R one class.*/static int registernativemethods (jnienv* env, const char* className, jninativemethod* gmethods, int n Ummethods) {Jclass Clazz;clazz = Env->findclass (className); if (clazz = = NULL) {return jni_false;} if (Env->registernatives (Clazz, Gmethods, Nummethods) < 0) {return jni_false;} return jni_true;} /** Register native methods for all classes we know about.*/static int registernatives (jnienv* env) {if (!registernativemet                       Hods (env, Jnireg_class, Gmethods,          sizeof (Gmethods)/sizeof (Gmethods[0]))) return Jni_false;return jni_true; extern "C" Jniexport jint jnicall jni_onload (javavm* vm, void* reserved) {jnienv* env = null;jint result = -1;if (vm->ge Tenv ((void**) &env, jni_version_1_4)! = JNI_OK) {return-1;} if (!registernatives (env)) {//register return-1;} /* Success--Return valid version number */result = Jni_version_1_4;return result;} The OnUnload method calls the extern "C" void Jni_onunload (javavm* vm, void* reserved) {} When the JNI component is released
4. Under JNI, add a name android.mkThe file.

/JNI/ANDROID.MK content is as follows

Local_path:= $ (call My-dir) include $ (clear_vars) local_module    : = libhellolocal_src_files: = Hellojni.cppinclude $ ( Build_shared_library)

5. The file structure of the case is as follows:


6. Perform the results


Extension topic:

How to print log to Logcat in CPP? There are several places to modify in CPP files and android.mk

1. Add Alogd, Aloge and other functions in the CPP file to define

#include <android/log.h> #define LOG_TAG "Jnidemo" #define ALOGE (...)     __android_log_print (Android_log_error, Log_tag, __va_args__); #define ALOGW (...)     __android_log_print (Android_log_warn, Log_tag, __va_args__); #define ALOGD (...)     __android_log_print (Android_log_debug, Log_tag, __va_args__); #define ALOGV (...)     __android_log_print (Android_log_verbose, Log_tag, __va_args__);

Using the debug level log output function alogd

extern "C" Jniexport jstring jnicall native_getversion (jnienv *env, Jobject thisobj) {   jstring szret;   Szret = Env->newstringutf ("V1.0");   ALOGD ("Native_getversion");   return Szret;}

2. Specify the load liblog.so library in the ANDROID.MK

Local_path:= $ (call My-dir) include $ (clear_vars) local_module    : = libhellolocal_src_files: = Hellojni.cpplocal_ Ldlibs: =-llog include $ (build_shared_library)




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.