Android Advanced Development JNI & NDK introduction and use

Android Advanced Development JNI & NDK introduction and use

Foreword

For areas of no contact, that is a challenge and an opportunity, not only to enhance their capabilities. Also be able to learn new technical knowledge

And learn new technologies, it is best to start from scratch in accordance with the system to learn! Better than has been looking for a quick fix method

For example, on the need (.a static library thief j8 nausea) hardware interaction Octopus and you must use the android NDK tool, using JNI bridge communication technology to achieve data exchange underlying C / C ++ and JAVA are local.

See technical information at the same time, we must first look at the latest official documentation! Because the upgrade may be updated because the IDE will use a different configuration!

NDK development in Android studio, the Android NDK is a set of low-level development kit c / c ++ libraries, however, to call the c / c ++ native functions in java, you need to use JNI to achieve.

What is JNI

JNI (Java Native Interface) is a java native interface, which is primarily to achieve a Java call c, c ++ like layer encapsulated native code interface. We all know that java is cross-platform development language, it's crazy platform features and capabilities lead to local interaction is not strong enough, and some of the operating system-related features in Java can not be completed, so Java JNI provides for Native Code and interact. By JNI, Java can be called c, c ++, contrast, c, c ++ can call Java related code.

JNI implementation of Java method calls the C layer process:
Here Insert Picture Description

FIG references from comparison JNA and the JNI

Why use JNI?

  1. Wifi hotspot phone can be expanded via JNI technology
  2. perform an efficient coder; a lot of computation (Need for Speed); universal decoder (ffmpeg); Opengl (3D rendering)
  3. Code reuse: ffmpeg, opencv (face recognition library), 7-zip
#include "com_atguigu_jnitests2_JNIS.h"
JNIEXPORT jstring JNICALL Java_com_atguigu_jnitests2_JNIS_helloJNI
(JNIEnv * env, jobject jobj) {
return (*env)->NewStringUTF(env, "Hello from C");
}

How to use Jni?

Learning C language - read the code

Jni familiar with the development process, familiar with the Android NDK

NDK Introduction

Definitions: Native Development Kit, is a tool for development kit NDK Android is part of Android, there is no direct relationship with Java

Role: rapid development of C, C ++ dynamic library, and automatically packaged into APK and applications together so

JNI can be used with a native code (e.g., C, C ++) interact by NDK Android

Scenario: In the case of Android scene using JNI

Namely the development of Android features require native code (C / C ++) to achieve

JNI is a protocol, the equivalent of a bridge

Java Native Interface: java local development interface

It allows java and C / C ++ code to achieve through JNI intermodulation

NDK is provided by Google in Android Development Kit

There are three main methods to compile the code using the NDK:

NDK development process

1, written in native code inside java

2. Create a directory in the main directory jni / cpp file or folder, including files created .c or .cpp class is c / c ++ file, use the command generate headers; (CMake way if the project will not generate a header created by default file)

3. The name of the configuration dynamic link library

4, load dynamic link library

5, the use of

NDK two kinds of processes commonly used in two ways nkd-build and compile code CMake slightly different configuration of the installation.


NDK development process ndk-build building

1. Installation Configuration NDK

1) Unzip the zip package NDK to non-Chinese directory

2) Configuration path: after extracting the root of the NDK -----> ndk-build

2. AS configuration related to the NDK

1). Local.properties adding configure

ndk.dir = G: \ android NDK-r10

2). Gradle.properties adding configure

​ android.useDeprecatedNdk=true

3. Write the native method:
public class JNIS {
		public native String helloJNI();
}

4. Define corresponding JNI

1) Create a folder in the main jni

2) The method of generating a corresponding native state headers JNI functions: command window, enter Folder java

			执行命令: javah com.atguigu.jnitests2.JNIS

			生成头文件: com_atguigu_jnitests2_JNIS.h
			
			函数声明: JNIEXPORT jstring JNICALL Java_com_atguigu_jnitests2_JNIS_helloJNI(JNIEnv *, jobject);
Two ways to generate 4.1 headers

​ 1.在\NDKDemo\app\src\main\java

Execute the command: javah com.atguigu.ndkdemo.JNI (copy of the full class name, Class name right in the file -> copy Reference get com.thisfeng.ndkdemo2.JNI)

.H header file generated in the current java directory, copy it into the directory or jni C cpp files and directories stored unity)

(Construction CMake fact, it may not generate a header file, a corresponding method C can be directly created by fast IDE)

2. Another project is performed in the build / intermaediates / classes / debug / lower

Command: . Javah -jni -classpath classpath JNI class

3) The generated header files transferred to the jni folder (AS CMake build should be stored in a unified way cpp file directory)

. 4) corresponding to the definition in the jni function file: test.c

#include "com_atguigu_jnitests2_JNIS.h"

JNIEXPORT jstring JNICALL Java_com_atguigu_jnitests2_JNIS_helloJNI 

(JNIEnv * env, jobject jobj) { 

return (*env)->NewStringUTF(env, "Hello from C"); 

}

5) create an empty file in the C jni folder: empty.c

Description: This is the AS bug, you must be at least two C files to compile (if there is try)

5. Specify different CPU compiled
defaultConfig {

ndk{

moduleName "HelloJni" //so文件: lib+moduleName+.so ( CMake 方式可不 定义? 但是会在 CMakeList 中去配置)

abiFilters "armeabi", "armeabi-v7a", "x86" //cpu的类型

}

}
  1. Compiled dynamic link files in different platforms

    1) Perform rebuild, so the file generated

    2) so the file directory:. Build \ intermediates \ ndk \ debug \ lib ...

  2. Call native methods:

    1) Load the document so the class where the native method

static {

System.loadLibrary("HelloJni");

}

2) call the native method in an Activity:

String result = new JNIS().helloJNI();

Log.e("TAG", "result="+result);

This completes the ndk-build compiler arranged to use as above. Under the following terms


NDK development process to build CMake

1 Introduction

Android NDK supports the use CMake to compile the application of C and C ++ code. C / C ++ project is currently in the AS are newly created based on CMake build, the following records how CMake for NDK.

Currently it does not support using CMake and ndk-build at the same time in the same module.

Android Studio from CMake since version 2.2, by NDK CMake and the C / C ++ code into the underlying database, and then compiled with the packaged library Gradle to the APK. Before CMake is a cross-platform build system CMake introduced in Android Studio, it has been in wide use.

2. Install and configure the NDK and CMake Click to view the official website

Note : If you ndk-bundle the NDK installation folder, it will appear in the label as NDK list. If you are using Gradle 3.5 version or later, you can check or uncheck the checkbox. Uncheck the box unloads NDK installed, free up disk space, and check boxes disappear from the list. If you uninstall the old NDK, please projects local.properties remove the file ndk.dir value, which is now abandoned.

Here Insert Picture Description

3. Configure CMake Click to view the official website

CMake build script is a plain text file, you must name it CMakeLists.txt, and which contains CMake build commands you need to use the C / C ++ libraries. If your native source code files have not CMake build scripts, you need to create a self, and which include the appropriate CMake command.

Once you download the NDK and CMake configuration, it is best to manually create a C / C ++ project will be a complete default configuration.

4. The Gradle linked to your native library

build.gradle File reference

   android {
      ...
      defaultConfig {...}
      buildTypes {...}

      // Encapsulates your external native build configurations.
      externalNativeBuild {

        // Encapsulates your CMake build configurations.
        cmake {

          // Provides a relative path to your CMake build script.
          path "CMakeLists.txt"
        }
      }
    }
    

The problems encountered

If you accidentally uninstalled before legacy NDK, please projects local.properties remove the file ndk.dir value, which is now abandoned.

Otherwise it will not pass the straight build error due. NDK go find the original

Given as follows:

A problem occurred configuring project ':app'. 

\> NDK not configured. Download it with SDK manager. Preferred NDK version is '20.0.5594570'. Log: /Users/thisfeng/Android/MyDemos/NewNDKDemo2/app/.cxx/ndk_locator_record.json 

So you want to use a specific download NDK (side by side)

This means that you need to install the specified version of the NDK version is '20 .0.5594570 ', as shown above, click on the bottom right show Packge details.

The use ndk-build way as in AS, NDK must configure local.properties configuration file:

ndk.dir=/Users/thisfeng/Library/Android/sdk/ndk-bundle 

After 3.5 and must be in local.properties remove file ndk.dir value, which is now abandoned.

Both constructs ways script file corresponding to:

​ CMake CMakeLists.txt

NDK-build Android.mk

Note: AS if the old version of the NDK is deprecated (Obsolete) After, we need to use the new. Re-download, mainly to use the ladder! Update

Here Insert Picture Description
CMake build resulting .so file here. When installation package will automatically scored apk

.so file is a dynamic link library (typically corresponding to a third party SDK needs to import different architectures libs .so files when accessing, this file is used by the third party SDK inside and some C / C ++ library function interaction)

.a files are static libraries (some third party will provide a header file and .a static library for you, look ignorant do not know how to use force)

(Cmake configuration .a library)


These are the two constructs, are now official default to create a new C / C ++ project is building with CMake, recommended CMake.

Published 25 original articles · won praise 19 · views 40000 +

Guess you like

Origin blog.csdn.net/a23006239/article/details/104881077