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. Other options are available with a preset value.

1. Slightly change the main activity configuration layout/activity_main.xml, in TextView add the ID named title (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 to the mainactivity.java loading library library? A native function is called getversion.

Write the following example:

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 such as the following

#include <jni.h> #include <stdio.h> #define JNIREG_CLASS "com/example/jnidemo/mainactivity"//   Specifies the class extern "C" Jniexport jstring jnicall native_getversion (jnienv *env, Jobject thisobj) to be registered {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 such as the following

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


Note:

Edit the process, if it happens for example the following bug

Cannot run Program "Ndk-build": Unknown reasonerror:program "Ndk-build" was not found in PATHPATH=[/USR/LIB/LIGHTDM/LIGHTD M:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/lib/jvm/jdk1.6.0_38/bin]

Please fill in the NDK installation path at WINDOW-&GT;PREFERENCES-&GT;ANDROID-&GT;NDK-&GT;NDL location


For example, the following bug

/opt/android/android-ndk-r9b/ndk-build cleanandroid NDK:WARNING:APP_PLATFORM android-19 is larger than Android: Minsdkversion in/{project_folder}/androidmanifest.xml   

Please change Androidmanifest.xml's minsdkversion or go to file->properties->android to change the SDK version number.


Other possible settings for editing results:

C + + Build Toolchain must choose Android GCC Compiler


To confirm that C + + Build command is Ndk-build



Extension topic:

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

1. Add to CPP file? ALOGD, the definition of aloge and other functions

#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__);

Log output functions using the debug level are alogd as follows

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)




Android JNI Programming Demo with Eclipse

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.