Android Studio NDK and so file development

Source: Internet
Author: User

PrefaceWhat is the NDK?

The NDK full name is native development KIT,NDK offers a range of tools to help developers quickly develop C (or C + +) dynamic libraries and automatically package so and Java applications together as APK. The NDK integrates a cross compiler (a cross compiler requires a UNIX or Linux system environment), and provides the corresponding MK file isolation CPU, platform, ABI, and other differences, developers simply need to modify the Mk file ("which files need to compile", "compile feature requirements", etc.), you can create a so.

Why use the NDK?

1, the protection of the Code. Because the Java layer Code of the APK is very easy to decompile, the C + + library is more difficult to reverse.
2. It is easy to use the existing open Source library. Most of the existing open source libraries are written in C + + code.
3, improve the execution efficiency of the procedure. Use c development for application logic that requires high performance to improve application execution efficiency.
4, easy to transplant. The library can be used in other embedded platforms easily.

What is JNI?

The full name of JNI is Java Native Interface, which provides a number of APIs that enable the communication of Java and other languages (mainly C and C + +).

Why use JNI?

The purpose of JNI is to enable Java methods to invoke some of the functions implemented by C.

What is the so file in Android?

The so file used in Android is a C + + library of functions. In the Jni of Android, the corresponding C language must first be packaged into so library and then imported into the Lib folder for Java to call.

Android Studio ndk and so file developmentNDK Installation and configurationNDK Installation

Android Studio started from 1.3 Beta1 and supported the NDK. is not supported before, so we recommend using the new version of the editor.

Right-click current project = Open Moudle Setting = Android SDK Location

If not installed, click Install download;

Then configure the environment variables;

Configuring environment Variables

The installed NDK is typically located in the Ndk-bundle under your SDK folder.

For example, I am here: D:\SDK\ndk-bundle (such as), you can see there are ndk-build files, the following compile the time we will use.


Then configure the path to your system variable's path, as follows:

1. Create Ndk_root in the system environment variable


2. Append the Ndk_root to the PATH environment variable--%ndk_root%

After adding to open cmd, enter the Ndk-build, the following is said to be successful (online said to be successful, although the display seems to be some error message, but the post-run time is not a problem can be compiled successfully).

So Library developmentNew Local Method

As below, a method has been established in Mainactiviy.java

public native String getStrFromJNI();

You can see that the declaration of this method has the native keyword, which means that this method is a local method, which means that the method Getstrfromjni () is implemented by local code (c + + +) and is only declared in Java code.

compile the class to get the corresponding. h file

switch to terminal and go to the project's Java directory (as shown), and then enter

Javah-jni-encoding Utf-8 package name. Class name (as shown).

After the compilation is successful, the project can see the compiled. h file, which is just to assist us in writing the corresponding. c file, which is deleted when it is finished.

The code for the file is as follows:

/* Don't EDIT this file-it are machine generated */#include <jni.h>/* Header for class Cn_handsomedragon_testndk_m Ainactivity */#ifndef _included_cn_handsomedragon_testndk_mainactivity#define _INCLUDED_CN_HANDSOMEDRAGON_TESTNDK _mainactivity#ifdef __cplusplusextern "C" {#endif/* * Class:     cn_handsomedragon_testndk_mainactivity * Method:    Getstrfromjni * Signature: () ljava/lang/string; */jniexport jstring Jnicall Java_cn_handsomedragon_testndk_ Mainactivity_getstrfromjni  (jnienv *, jobject); #ifdef __cplusplus} #endif #endif

In fact, the important part is this code:

Jniexport jstring jnicall java_cn_handsomedragon_testndk_mainactivity_getstrfromjni  (JNIENV *, jobject);

Careful observation can be seen that he is following the "Java_ package name class name local method name" to organize (after understanding these we can later do not generate. h file and then go directly to write. c files).

writing a. c file

Then we switch to project and create a new JNI folder in the app directory and create a demo.c C file in it (as shown).

Write the most basic test code in the DEMO.C file:

#include <string.h> #include <jni.h>jstringjava_cn_handsomedragon_testndk_mainactivity_getstrfromjni ( JNIEnv *env,jobject thiz) {    return  (*env)->newstringutf (env, "I ' m Str!");}

This is to see that we are using the line of code in. h, slightly modified to the above format is what we need. c file.

Writing android.mk Files

Create a new android.mk (must be this name android.mk) file under the JNI directory, as shown in:

Edit the ANDROID.MK code:

Local_path: = $ (call My-dir) include $ (clear_vars) local_module        : = Demo         //The name of the so library to be generated, but actually LIBDEMO.SOLOCAL_SRC_ Files     : = demo.c       //file to be used, the demo.c file you just wrote include $ (build_shared_library)

Generate so file

In the console, go to the project's app directory and enter Ndk-build (shown below) to compile successfully without problems.

After compiling the project, you can see the Libs and obj folders generated in the app directory, where Libs is useful and the Obj folder is useless to delete. The generated libdemo.so file can be seen in the Libs.

two necessary settings

1. To set the NDK path in local.properties , my ndk example is as follows:

2, in the app's Build.gradle android node settings:

These two places are necessary to be able to make a happy call to the so file we generated after the modification is complete.

using so files

In Mainactivity.java, load the so file and invoke the code as follows:

This library demo (the full name is libdemo.so) will be loaded the first time you use the class mainactivity. (The code of the Static code block declaration is executed prior to the OnCreate method)

Look at the output of the console and you can see the printed string:

This means that the so library is used successfully, and the previous JNI folder and the previously generated. h file can be completely deleted. Of course, this so library you have to do a good job of documenting the document, or you will probably forget that the local method can be called.

Android Studio NDK and so file 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.