Android Zero-starting JNI development

Source: Internet
Author: User

Reprint Annotated Source: http://blog.csdn.net/xiaohanluo/article/details/55193157

This article is an introduction to the JNI development of Mac-based Android studio.

Andorid Official JNI Documentation

Android Official JNI Instance Document

JNI Wikipedia

JNI Handbook English version

JNI Manual Chinese version

Oracleg Official JNI Documentation

1. NDK Installation and Environment configuration
    • Android Studio 2.2 and above reference links
      Getting Started with the NDK

    • Mac End Hand RIP NDK environment build

      • Select NDK version to download NDK Downloads
      • Unzip the download file
      • Set the environment to the user's root directory, open the. bash_profile file, set the NDK environment, refer to the article Mac OS x configuration environment variables
    • Windows hand torn NDK environment is built, because C + + is compiled and run in GCC environment, so the Windows environment needs Cygwin simulation Linux compilation environment, reference http://www.jb51.net/softjc/159272.html

After the environment configuration is complete, use the Ndk-build directive to see if the configuration was successful.

Perform effects under Mac:

> ndk-build                                                                                                                                         notdirectory !    thevariabletotoit.    

Once the NDK environment is set up, it's ready to start.

2. Define Java classes with native methods
publicclass JNIDemoUtil {    privategetString(String input);}
3. Generate class file

build -> rebuildRebuild the project, generate the class file, and the class file in the <壳工程>/build/classes/debug directory.


Figure-1 class directory structure Figure 4. Generate the. h header File

Go to the <壳工程>/build/classes/debug directory to execute the following command

# -classpath指定类的路径javah -classpath . -jni {包名.类名}

For example, javah -classpath . -jni com.kyo.jnidemo.jni.JNIDemoUtil A. h file is generated.


Figure-2 H file directory Figure 5. Writing a C + + file

The concrete realization of native

#include <stdlib.h>#include <jni.h>#include "com_kyo_jnidemo_jni_JNIDemoUtil.h"#ifdef __cplusplus"C" {#endifjstring Java_com_kyo_jnidemo_jni_JNIDemoUtil_getString(JNIEnv *env, jclass obj) {    return"hello world");}#ifdef __cplusplus}#endif
6. Create a. So dynamic library

I got the H-header file and the concrete implementation of the C + + file, followed by the generation of. So dynamic libraries, depending on the directory you put in three different ways.

    • Placed in the project's root directory JNI
    • In the internal sub-file of the project
    • Put it in the /src/main/jni table of contents
6.1/C + + code in root directory JNI
Figure-3 root directory generation so

Create a new Mk file and set some properties.

LOCAL_MODULE:${call my-dir}/include${CLEAR_VARS}LOCAL_SRC_FILES:/Users/wang/WorkPlace/MyWork/JNIDemo/jni/JNIDemoUtil.cLOCAL_MODULE = libJNIDemoinclude${BUILD_SHARED_LIBRARY}

Into the JNI directory, using ndk-build instructions, will be automatically generated in the project root directory, libs obj two directories, where Libs, the directory has so library.


Figure-4 run result diagram

Note: Only JNI placed in the engineering root directory can be compiled using the ndk-build directive.

6.2 c/cc++ code in other catalogs within the project
Figure-5 non-root directory connection structure diagram



Create a new Application.mk file in the project root directory.

APP_BUILD_SCRIPT:/Users/wang/WorkPlace/MyWork/JNIDemo/jni_c/src/Android.mk# 因为针对多个CPU架构会生成多个so库,使用APP_ABI限定生成支持某种CPU架构的so库APP_ABI:= armeabi

Create a new Android.mk file in the c/cc++ code directory

LOCAL_MODULE:${call my-dir}/include${CLEAR_VARS}LOCAL_SRC_FILES:/Users/wang/WorkPlace/MyWork/JNIDemo/jni_c/src/JNIDemoUtil.cLOCAL_MODULE = libJNIDemoinclude${BUILD_SHARED_LIBRARY}

Execute the following command at the root of the project (you can go directly to the C + + source directory to execute the ndk-build build so library), will be automatically generated in the project root directory, libs obj two directories, where Libs, the directory has so library.

ndk-build NDK_PROJECT_PATH={工程目录} NDK_APPLICATION_MK={工程的Applicaion.mk目录}

Instruction run result diagram:


Figure-6 Run result diagram

APPLICATION.MK Specifies the compiled MK, and android.mk specifies some of the properties of the compilation, including compiling the source files and so on, which can be flexibly changed

6.3/C + + is placed src/main/jniDirectory under
Figure 7 Auto-generate so catalog diagram



local.propertiesAdd the NDK path in, my below.

sdk.dir=/Users/wang/Android/Android_SDKndk.dir=/Users/wang/Android/Android_NDK_r13b

In the shell engineering (usually App/build.gradle) build.gradle configuration generated so library name, find defaultconfig this node, add the following content.

defaultConfig {    ...    ndk {        "libJNIDemoJni" // so库名        "armeabi" // 指定生成的CPU架构对应的so库    }}

Added to the gradle.properties file.

android.useDeprecatedNdk=true

Then the rebuild project will automatically generate so dynamic libraries, under the <壳工程>/build/intermedistes/ndk directory, directories such as:


Figure 8 Automatic generation of so directory 7. Load So Library

The resulting so library is in the <壳工程>/src/main/jniLibs directory.

Also JNIDemoUtil load so library code in.

publicclass JNIDemoUtil {    // 注意库的名字前面没有lib    static {        System.loadLibrary("JNIDemo");    }    publicstaticgetString();}
8. Compile and run

After the preparation is done, you can run it directly.

publicvoidonClick(View v) {    int id = v.getId();    if(id == R.id.jni_demo_btn){        mInfoTv.setText(JNIDemoUtil.getString());    }}

Run the result diagram:


Figure 9 Running results Figure 9. Question Answer

Java.lang.UnsatisfiedLinkError:Couldn ' t load XXX indlibrary

    • Verify that the library name is correct when LoadLibrary
    • So directory is problematic, [click here to see Settings]http://blog.csdn.net/yy1300326388/article/details/46291417

Android ndk:could not find application project directory!
Android ndk:please define the Ndk_project_path variable to the it.

Compile with the following directives

ndk-build NDK_PROJECT_PATH={工程目录} NDK_APPLICATION_MK={工程的Applicaion.mk目录}

Enclosed Demo Address: Https://github.com/Kyogirante/JNIDemo

10. Concluding remarks

This article has little to do with the variables and syntax, and so on, between C + + and Java, which are described in the next article. I am also in the process of learning to explore, if there are mistakes I hope you point out.

Android Zero-starting JNI development

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.