New JNI project in Eclipse

Source: Internet
Author: User
Tags naming convention

1. What is the NDK

Online a lot of say, the full name is Android Native Developer Kit, is a tool collection, I understand can be packaged into a. so file

This is the directory structure, to use the command ndk-build

Need to configure environment variables

Configuration successfully entered in CMD Ndk-build the following information appears

2. What JNI

JNI full name is Java Native Interface, literally means Java's local interface, we know that Java is a platform, so Java writing program should be platform-independent,

So in Java if you want to invoke a local library requires a dedicated interface, I can understand as a set of call mechanism or protocol.

Steps for JNI Programming:

  1.java: use keyword native to declare A/C + + method. Import Lib Library:

 Public class Native {    static{        system.loadlibrary ("Hellojava");    }      Public Static native String getString ();}

Note that the "Hellojava" Here is your new C/s + + file name, and do not write anything extra. Now that we have defined a class that is Native.java, then we are going to turn this class into a header file. However, Google's Android Studio 2.2 version can be built directly after a support C + + project. This is not to be mentioned here first.

First, you need to generate a. class file for Native.java compilation. The Javacto use here. But you can also run it directly. Eclipse will proactively help you compile the build. Class, open cmd

The generated Native.class

Note Here the use of Javac I direct CD to the directory of this class.

After the. class file is generated, use the other JDK tool to generate the. h file Javah

Also in cmd: Enter Javah-help to view usage help

[Options] is an optional item,<classes> is a must item. This is the native.class we created earlier.

Now we need to determine the path to load the class and the output directory. Note the space between each paragraph, error-prone

The suffix of the class does not need to be written. After executing this command, the corresponding. h file is generated in the current directory.

The right-click project name in Eclipse, Refresh (F5) is displayed below

Now that our Java layer is done, the next step is to implement the declared method in JNI.

2.Jni Layer: 

Create a new JNI directory in the project and move the. h file over

Create a new hellojava.c. C Source file Here we implement the native method declared in the Java layer

#include <stdio.h><stdlib.h><jni.h>jniexport jstring jnicall java_com_ Example_helloc_native_getstring  *env, Jclass j) {    return (**env). Newstringutf (env, "Hello java!" );}

The name of the function is too complex and too lame. In fact, JNI has a naming convention that we don't care about now, and this function name can be copied directly from the previously generated. h file.
Here is the contents of the. h file

 /*   do not EDIT this file-it are machine Generated  */  #include  <jni.h >/*   Header for class Com_example_helloc_ Native  */  #ifndef _included_com_example _helloc_native#define _included_com_example_helloc_native#ifdef __cplusplusextern  "C"  {#endif  /*   * CLASS:COM_EXAMPLE_HELLOC_ Native * method:getstring * Signature: () ljava/lang/string;  */ jniexport jstring jnicall java_com_ Example_helloc_native_getstring (jnienv  * 

There is only a function declaration, copy this declaration, we can just implement the function body in JNI. The specific programming method is not mentioned here first, here just returns a string

Some C libraries have been integrated in the NDK. When we're done, we need to turn. C into a. So library that Linux systems can use. This work is done by the NDK, specifically as follows:

The ndk-build directive needs to be executed in the project directory, but it is not specified in what subdirectories, all effects are the same. The directive generates. so files for. C or C + + files, and is two copies, one in \project Path\obj\local\armeabi, which is larger, contains debug information and will not be published with the app. The other one is smaller \ Project path \libs\armeabi, which will be released along with the APK. Compile results

The. So files supported by each platform have been generated and the Libs of the project catalog has not yet appeared. so files,

Need to right-click Project Refresh (F5) will appear, here the system will automatically add "Lib" prefix. But note that when you import a library in the Java layer, do not write "Libhellojava" to write:

Static {

System. loadLibrary ("Hellojava");

}

Executes the result after completion. This is the Android code

 Public classMainactivityextendsActivity { PublicButton btnshow;  PublicTextView tvShow; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Btnshow=(Button) Findviewbyid (r.id.btn_show); TvShow=(TextView) Findviewbyid (r.id.tv_show); Btnshow.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method StubTvshow.settext (native.getstring ());    }        }); }}

Results

In addition, you need to write a. mk file before executing ndk-build. specific as follows:

Create a new android.mk file in JNI with the following content:

Local_path: = $ (call my-dir) include $ (clear_vars) local_module    := hellojavalocal_src_files:= hellojava.c#local_ldlibs    :=-llog-ljnigraphicsinclude $ (build_shared_library)

The specific explanations are as follows (borrowing one for the great God):

Local_path: = $ (call My-dir)

The Android.mk file must first define the Local_path variable. It is used to find source files in the development tree. In this example, the macro function ' My-dir ', provided by the compilation system, is used to return the current path (that is , The directory containing the android.mk file).

Include $ (clear_vars)

Clear_vars is provided by the build system, specifying that GNU makefile clears many local_xxx variables for you (such as Local_module, Local_src_files, local_static_libraries, etc...) , except Local_path. This is necessary because all the compilation control files are in the same GNU make execution environment, and all the variables are global.

Local_module: = Native

To compile the target object, the Local_module variable must be defined to identify each module that you describe in the Android.mk file. The name must be unique and does not contain any spaces.

Local_src_files: = native.c

The Local_src_files variable must contain a C or C + + source code file that will be compiled into a module. Note that you do not have to list header files and include files here, because the compilation system will automatically find the dependent files for you; Just list the source code files that are passed directly to the compiler.

Note that the default C + + source file extension is '. cpp '. It is also possible to specify a different extension, as long as the local_default_cpp_extension variable is defined, do not forget to start the small dot (i.e. '. Cxx ' instead of ' cxx ')

Include $ (build_shared_library)

Build_shared_library means compiling a shared library, which is a compiled system-supplied variable, pointing to a GNU makefile script, responsible for collecting since the last call to ' include $ (clear_vars) ', defined in Local_ XXX variable, and decide what to compile and how to do it correctly. There are also build_static_library variable representations to generate a static library: lib$ (Local_module). A, build_executable represents the build executable.

New JNI project in Eclipse

Related Article

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.