Learn jni--android using JNI call C

Source: Internet
Author: User

first, what is JNI:

jni is Java Native Interface from J ava1.1 begins, the Java Native Interface (JNI) standard becomes the java Part of the platform that allows Java code to interact with code written in other languages. JNI was initially designed for local compiled languages, especially C and C + +, but it does not prevent you from using other languages, as long as the calling convention is supported.

1. Benefits of using JNI:

A, you can use JNI to implement the "local Method" (native methods), and call them in Java programs, generally called C in Java functions, but also can use C to call the Java method, so that you can reuse a lot of previously written code.

b, JNI supports a "calling interface" (invocation interface), which allows you to embed a JVM in a local program. Local programs can link a local library that implements the JVM, and then use the "Invoke interface" to execute a software module written in the Java language.

2. The side effects of using JNI:

A, the well-known Java portability may be destroyed after the use of JNI, the program no longer cross the platform, the reason is very simple, one operating system on the local method is likely to not work on another platform, so the Java code using these local methods is also unable to run on another platform.

b, the program is no longer absolutely secure, improper use of local code may cause the entire program to crash.

It is a good practice to have local methods of invocation focused only on the few classes of the project you write, which can reduce the coupling between Java and C code and improve the maintainability of the code.


Second, Java calls C to achieve a simple helloworld: (Take Android+eclipse as an example)


Okay, it's helloworld! again.


Here we take the Android project as an example.

Before you actually start, let's look at the basic process:

1, first create a Java file: Helloworld.java, and declare a local method, note to add a keyword native, here we do not write his implementation, concrete implementation to C:

public native void HelloWorld ();

2. Then we can use the Javah directive to generate the. h header file for the corresponding Java file (c to use):

Here I have already set up the environment by default, if not can see: http://www.cnblogs.com/baronzhao/archive/2012/07/10/2585181.html

opening Cygwin, we first entered the corresponding project in the SRC directory, where I was using the Cygwin opened the catalogue: /cygdrive/d/android_workspace/jni_day19/exercise/src

then execute: Javah-jni com.example.exercise.MainActivity , where com.example.exercise.MainActivity to Mainactivity.java the full class name

Normal will generate a. h header file in the SRC directory: Com_example_exercise_mainactivity.h , the contents are:

/* Don't EDIT this file-it are machine generated */#include <jni.h>/* Header for class Com_example_exercise_mainac tivity */#ifndef _included_com_example_exercise_mainactivity#define _included_com_example_exercise_mainactivity# ifdef __cplusplusextern "C" {#endif/* * Class:     com_example_exercise_mainactivity * Method:    getstr * Signature: () ljava/lang/string; */jniexport jstring jnicall java_com_example_exercise_mainactivity_getstr (jnienv *, jobject); #ifdef __cplusplus}# Endif#endif


In fact, the above-mentioned endif and other macro definitions are not necessary, the key part is only one include<jni.h> and jniexport jstring jnicall java_com_example_exercise_mainactivity_getstr (jnienv *, jobject);

jni.h is the header file for the corresponding type and function in C of the type and method defined by JNI, which is required.

second, jniexport jstring jnicall java_com_example_exercise_mainactivity_getstr (JNIENV *, jobject); This sentence except jniexport can be removed, the others must be consistent, presumably the notation is: return type (here is void) Java_ full class name (. _) _ Method name (jnienv* env,jobject OJB) ;


3. Create a new folder named Jni in the project and cut the. h file you just generated into the Jni folder and write the appropriate. C/.cpp code.

Here is a small detail, sometimes eclipse will have a yellow question mark in the # include <jni.h> here warning, can't find this corresponding jni.h file, we can right click on the project and then click Androidtools-> Addnativesupport, such as:



A dialog box pops up when you finish clicking:



Here we can directly write the so file name that we want to generate later, this file name is associated with the. c file, here we choose Hello, after clicking Finish, we find that eclipse automatically generated two new files in the Jni folder: android.mk and the Hello.cpp file

Where the Android.mk file is:

Local_path: = $ (call My-dir) include $ (clear_vars) #对应的是打包成函数库的名字 local_module    : = Hello #src目录, file corresponding to C code LOCAL_SRC_ FILES: = Hello.cpp include $ (build_shared_library)

The purpose of this file is to specify the rules for generating. so files.

and Hello.cpp file is we need to actually write C code of the file, in this case, we will implement just in the header file jstring jnicall java_com_example_exercise_mainactivity_getstr (JNIENV *, jobject); this function.

In fact, what we're going to do here is very simple, and our goal is to return a string in this function: "Hello from c!", which actually requires a method defined in jni.h: jstring (*NEWSTRINGUTF) (jnienv*, const char*); its function is to return a jstring string

#include <stdio.h> #include "com_example_err_mainactivity.h"//jstring     (*newstringutf) (jnienv*, const char *); Jniexport jstring jnicall Java_com_example_err_mainactivity_helloworld (jnienv * env, Jobject obj) {return (*env). Newstringutf ("Hello from c!");}


4, after all we need to do is to generate. So library files, in the case of the system environment variable configuration, directly open the CMD, into the corresponding project directory, execute ndk-build can generate the corresponding library file:libhello.so .


in fact, this file will appear in the project folder: obj/local/armeabi/ folder.

Now that the library has been built, the next task is to call the function

5. Call this. so file in Mainactiviy.java.

We can then mainactiviy.java the file, define a button, corresponding to the Click event Cilck, whenever clicked, call this method, return the string "Hello from c!" In the form of toast, it is important to note that we need to first load the. So library file that was just generated, which is loaded with a static block, system.loadlibrary ("Hello"); Note here that we don't need to write libhello.so, just write Hello :

public class Mainactivity extends Activity {public native String helloWorld (); static {system.loadlibrary ("Hello");} @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);} public void Click (View view) {String HelloWorld = HelloWorld (); System.out.println (HelloWorld); Toast.maketext (Getapplicationcontext (), HelloWorld, Toast.length_long). Show ();}}


Effect:












Learn jni--android using JNI call C

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.