Android JNI/NDK Development (a) is the ndk really difficult?

Source: Internet
Author: User

An idle youth, needy age. The carefree and unrestrained university time has led to today's not even C + + programming. As a programmer, it's embarrassing not to say it in C + +. Recently viewed the company recruitment information (Android position), found that the requirements for NDK development is becoming more and more common. I am learning Java, engaged in Android development, the bottom of the android is a little bit afraid of things, because it has not been involved, but we know, can not be afraid to give up. As I have once signed: now to act, more than the hesitation of the people a step faster.

Back to the chase, is it really hard to develop NDK? Actually not, feel difficult is because you did not understand, do not understand is because did not learn. Then come on.

NDK: What is the NDK

The Android NDK (Native Development Kit) is a set of tools that allow you to implement parts of your application in the same way as the C + + language.

NDK: When to use the NDK

    • Improve performance. In some cases, the efficiency of using a/C + + processing logic algorithm is higher than Java (Image correlation processing algorithm, etc.)
    • Use a third-party library. Many third-party libraries are written in the C + + language, and Android applications need to use existing third-party libraries such as FFmpeg, OpenCV, and so on.
    • The underlying programming. For example, an application does not rely on Dalvik Java virtual machines.

In other words, it is attractive to see the high performance of the light. Get started, don't say those imaginary, run first.

1. Build the NDK development environment

No words Baidu, this is not difficult, the second configuration. 1. Download ndk file, unzip; 2. Configure to environment variable; 3.cmd test NDK is installed and configured successfully

2. Implementation of the first NDK project

Target implementation: pass two int values from Android plane to the bottom, compare the size of two values using C + + processing, and return the result information (string) for Android use.
Project questions: How does Android Pass the Java data type to C + + for use? How do I pass a C + + data type to Java? What is the bridge in the middle?
Project Analysis: Android passes the Java data type to the native layer, which is converted to a data type that is available from C + + via JNI "encoding", and vice versa, using JNI as a bridge to communicate Java and C + +

2.1 Native (Android level development)

Create an Android project.
hellondk defines the native interface, computes the size of two int in C + +, returns the result information string

publicnativegetMaxInt(intint second);

The so library is invoked in hellondk with static blocks.

static {        System.loadLibrary("hi-ndk");    }

hellondk(Activity) Full code

 Public  class hellondk extends Activity {    Static{System.loadlibrary ("HI-NDK");//"HI-NDK" so name}@Override     Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); TextView TV =NewTextView ( This); Tv.settext (Getmaxint ( the,Ten));    Setcontentview (TV); } Public nativeStringGetmaxint(intFirstintsecond);}
2.2 JNI (for Android and C + + connection layer processing)

First configure JNI to create a new jni folder in your project. JNI contains android.mk,application.mk, header file [cn_r_ndk_android_hellondk.h],C + + file

New android.mk,application.mk, the contents of these two files do not have to be remembered, the configuration file, understand what the meaning is good, can also be copied from the ndk sample project, unzip The NDK follows the package with sample to find the android.mkin the hello-jni replication project,application.mk

android.mk file code. (See notes in the file)

LOCAL_PATH:$(call my-dir)include$(CLEAR_VARS)LOCAL_MODULE    := hi-ndk   #so项目名称LOCAL_SRC_FILES:= hi-ndk.cpp#资源文件名称,对应的c/c++代码文件include$(BUILD_SHARED_LIBRARY)

application.mk file code. (See notes in the file)

APP_ABI := all#APP_ABI:= armeabi armeabi-v7a x86 mips mips-r2 mips-r2-sf#如果是普通arm处理器的Android手机,使用APP_ABI := armeabi;#如果是x86处理器的,使用APP_ABI := x86,等等。#如果APP_ABI := all,会编译所有指令的soAPP_STL := stlport_static#NDK中C++标准库、STL的配置#如未配置可能出现错误: fatal error: iostream: No such file or directory

header file [cn_r_ndk_android_hellondk.h]. C + + header file, which generates the header file via Javah . javah Command usage details, you can view the typing javah in cmd view

Generate header File mode: Open cmd panel, go directly to project src directory, then execute

javah-d. /jni CN.R.NDK.ANDROID.HELLONDK
Note: CN.R.NDK.ANDROID.HELLONDK is the full path to (defines the native interface) class

After successful execution, you can view [Cn_r_ndk_android_hellondk.h] in the jni folder

2.3/C + + (logical processing layer)

The first two steps complete the basic configuration, and now the next step is to write the logical code for the focus.
There are a few questions before you write the code:

How do 1.java data types and C + + data types get through?
Answer: Use JNI. As mentioned earlier, JNI is a bridge between Java and C + +, and JNI provides a specification for bridging the barriers between the two languages.

How does the 2.java data type translate to JNI?
Basic data type:

Reference type:

From the table above, it is not difficult to see that, through the JNI specification, the basic types in Java are converted to JNI data types, which are basically added with J.
Example: int:int, Jint

How do 3.JNI data types and C + + data types convert to each other?
It's a bit of a hassle, you need to check the data yourself. Learn how to handle strings and object types in JNI programming.
Let's take a look at the main code that needs to be explained. (here using the C + + language implementation, the introduction of the header file and so on, I am also learning the NDK, while learning C + +, so the C + + code written by the water, please do not laugh, trouble corrected out)

jstring Java_cn_r_ndk_android_HelloNdk_getMaxInt(JNIEnv * env, jobject thiz,        jint first, jint second) {    int first_j = first;    int second_j = second;    int max = maxInt(first_j, second_j);    /**     * int > string     */    string msg_result = xToString(max);    "the max number:";    string msg = msg_tip + msg_result;    constchar* msg_j_a = msg.c_str();    jstring msg_j = env->NewStringUTF(msg_j_a);    return msg_j;}

C + + language is similar to Java, I basically write code according to the Java idea

Here the basic data type Jint is converted directly to C + + int. Next, the method is called to calculate the maximum value of two digits. Here's what I want to spit out is that C + + adds int data type and string type together so troublesome, in Java string and int use + can be directly spliced. You need to use conversions several times in C + +.
We want to return the results of "the Max Number:xx" to Java. Used here

    env->NewStringUTF(msg_j_a);

Because the parameters received in the Newstringutf () method are of type char* ch , there are various conversions in the code.
I first convert int to string, then Stitch twostrings, then use string.c_str () to convert the string to char*, and finally call The Newstringutf () method returns jstring
Note: If you call JNI using C language, the method differs

(*env)->"Hello from JNI ! ");

The code about the C + + section does not say much here, because I am not very good, in case it is wrong, it is embarrassing. The reader can only be self-fathom.
About the data type "conversion" between C + + and Jni There are two points I'd like to share:
1. Basic data types can be converted directly ;
Several methods of 2.string type processing :

http://blog.csdn.net/xyang81/article/details/42066665

Check out the full version of the code hi-ndk.cpp

#include <iostream> #include <string> #include <jni.h> #include"Cn_r_ndk_android_hellondk.h"using namespace Std;//Function declarationintMaxInt (intFirstintsecond); string xtostring (intx); jstring java_cn_r_ndk_android_hellondk_getmaxint (jnienv * env, Jobject thiz, Jint First, jint second) {intFirst_j = First;intSecond_j = second;intmax = MaxInt (First_j, Second_j);/** * int > String * *String msg_result = Xtostring (max); String Msg_tip ="The max number:"; String msg = Msg_tip + Msg_result;Const Char* msg_j_a = Msg.c_str (); Jstring Msg_j = Env->newstringutf (msg_j_a);returnMsg_j;}/** * Compare two number size */intMaxInt (intFirstintSecond) {if(First > second) {returnFirst }Else{returnSecond }}/** * x converted to string */String Xtostring (intx) {Charch[Ten]; sprintf (CH,"%d", x); string result (CH);returnResult;}

OK, here the basic work is done, will it be a bit of a circle? Not the best, if the circle then take a rest, and then the idea, stop to think about the implementation steps:
1. Native (Android level development)
Description: "A class that defines the native method"
2. JNI (for Android and C + + connection layer processing)
Description: "A JNI folder with four important files, android.mk,application.mk, header files, C + + files"
3. C + + (logical processing layer)
Description: "java->jni;jni<->c++; Business logic Processing"
Does this look simple and clear? Three parts, a look at a brief description can know what each step to do, if still a blank go back to that step and see.

If there is no problem, then the final step,ndk-build compiled so file .

Compile the successful picture always look so natural, uniform.
People say the darkest before dawn, the most elusive before success. Yes, in this step you may also card for a long time, but do not be afraid, this part of the compilation error is basically a C + + file code problem, if the data type conversion problem can refer to the above mentioned two points, 1 basic data type direct use, 2.string problem reference links. If it is code logic and normative problems, then can only ask Niang, Patience Point, you always compile successfully. Say out not afraid of others jokes, that number conversion and string splicing requirements I got a long time, C + + language unfamiliar, just ask Baidu write finished.

After the compilation is successful, you can see the so file in the Lib folder named:hi-ndk

Would you like to ask me how Android uses this so file? How do I get the results from C + + computing?

In fact, in the beginning, the code inhellondk
Class static block load so file, note here do not write libhi-ndk.so , remove the front "Lib" and the following ". So", only need HI-NDK

static {        System.loadLibrary("hi-ndk");//"hi-ndk" so 名称    }

Method invocation

new TextView(this);tv.setText(getMaxInt(1510));

OK, is it hard to finish the first NDK project here? It's not that hard. With dim sum, everything is not too difficult, just see how much you want to do one thing. The joy of success is not bought by money, haha. It also learns the new language C + +. Why not?

What do not understand where you can leave a message to discuss, there are deficiencies in the area also look at the criticism.

Code download

Android JNI/NDK Development (a) is the ndk really difficult?

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.