In-depth understanding of Android (1) -- Understanding JNI and androidjni in Android

Source: Internet
Author: User

In-depth understanding of Android (1) -- Understanding JNI and androidjni in Android

I participated in the CSDN blog Star Selection. If sunshine Xiaoqiang's blog has helped you in the past period, I hope to vote for you, every day can cast once: http://vote.blog.csdn.net/blogstar2014/details? Username = lxq_xsyu # content

1. What is JNI?

JNI is the abbreviation of Java Native Interface (called locally in Java). Functions in Java programs can call functions written in Native (generally C/C ++ ), functions written in Native can call functions at the Java layer.

2. Why does JNI exist?

Java is cross-platform because Java virtual machines can be run on different platforms, while virtual machines run on specific platforms. In essence, Java is a cross-platform implemented through JNI technology, many grass-roots modules have already achieved excellent implementation before the birth of the Java language. To avoid repeated wheel creation, we need to use the JNI technology to use the existing modules.


Iii. Environment Construction on Mac OS

Here, we will describe how to set up the environment required on Max OS. For Windows and Linux, please search for relevant information.

1. Install JDK (omitted here ).

2. Install ADT (Android Develop Tools), including SDK and ADT plug-in,: http://pan.baidu.com/s/1o6OBIHG

3. You can download and install Xcode from the apple store for free ).

4. install Apache ANT (: http://ant.apache.org/bindownload.cgi) Detailed installation process can refer to: http://blog.csdn.net/song_hui_xiang/article/details/14315529

5. install GNU Make (installed by default, so you do not need to install it). You can run the make-version command to verify installation.

6. Install NDK (: http://pan.baidu.com/s/1i3l5L8T), unzip it, and create a file. bash_profile under the user root directory, and then add the following two lines (configure environment variables, You can temporarily do not configure ).

export ANDROID_NDK_HOME=/Users/lixiaoqiang/Documents/install_tools/ndk/android-ndk-r10cexport PATH=${PATH}:${ANDROID_NDK_HOME}
Note: The following address is the directory after extraction.

A Brief Introduction to the above development tools:

1. Apache Ant is a tool that automates software compilation, testing, deployment, and other steps. It is mostly used for software development in the Java environment.

2. NDK is a native Android development kit that supports developing Android applications in C/C ++ and other native programming languages. It provides header files, libraries, and cross-compilation tool chains.

4. The first example Program

Reprint please explain the source: http://blog.csdn.net/dawanganban

1. Specify the NDK path for eclipse


2. Import the sample code in Android NDK (import the hello-jni Project). If you have worked in Android development, you should be familiar with it.


3. Add native support to the Project

Project --> right-click --> Android Tools --> Add Native Support

This project actually contains a native project, so you can skip this step and Finish it directly.

4. Plug in the mobile phone (the simulator is too slow. We recommend using a real machine) to run the project. In the C/C ++ interface view, we can see the following information:

**** Build of configuration Default for project HelloJni ****/Users/lixiaoqiang/Documents/install_tools/ndk/android-ndk-r10c/ndk-build all Android NDK: WARNING: APP_PLATFORM android-19 is larger than android:minSdkVersion 3 in ./AndroidManifest.xml    [arm64-v8a] Gdbserver      : [aarch64-linux-android-4.9] libs/arm64-v8a/gdbserver[arm64-v8a] Gdbsetup       : libs/arm64-v8a/gdb.setup[x86_64] Gdbserver      : [x86_64-4.9] libs/x86_64/gdbserver[x86_64] Gdbsetup       : libs/x86_64/gdb.setup[mips64] Gdbserver      : [mips64el-linux-android-4.9] libs/mips64/gdbserver[mips64] Gdbsetup       : libs/mips64/gdb.setup[armeabi-v7a] Gdbserver      : [arm-linux-androideabi-4.6] libs/armeabi-v7a/gdbserver[armeabi-v7a] Gdbsetup       : libs/armeabi-v7a/gdb.setup[armeabi] Gdbserver      : [arm-linux-androideabi-4.6] libs/armeabi/gdbserver[armeabi] Gdbsetup       : libs/armeabi/gdb.setup[x86] Gdbserver      : [x86-4.6] libs/x86/gdbserver[x86] Gdbsetup       : libs/x86/gdb.setup[mips] Gdbserver      : [mipsel-linux-android-4.6] libs/mips/gdbserver[mips] Gdbsetup       : libs/mips/gdb.setup[arm64-v8a] Compile        : hello-jni <= hello-jni.c[arm64-v8a] SharedLibrary  : libhello-jni.so[arm64-v8a] Install        : libhello-jni.so => libs/arm64-v8a/libhello-jni.so[x86_64] Compile        : hello-jni <= hello-jni.c[x86_64] SharedLibrary  : libhello-jni.so[x86_64] Install        : libhello-jni.so => libs/x86_64/libhello-jni.so[mips64] Compile        : hello-jni <= hello-jni.c[mips64] SharedLibrary  : libhello-jni.so[mips64] Install        : libhello-jni.so => libs/mips64/libhello-jni.so[armeabi-v7a] Compile thumb  : hello-jni <= hello-jni.c[armeabi-v7a] SharedLibrary  : libhello-jni.so[armeabi-v7a] Install        : libhello-jni.so => libs/armeabi-v7a/libhello-jni.so[armeabi] Compile thumb  : hello-jni <= hello-jni.c[armeabi] SharedLibrary  : libhello-jni.so[armeabi] Install        : libhello-jni.so => libs/armeabi/libhello-jni.so[x86] Compile        : hello-jni <= hello-jni.c[x86] SharedLibrary  : libhello-jni.so[x86] Install        : libhello-jni.so => libs/x86/libhello-jni.so[mips] Compile        : hello-jni <= hello-jni.c[mips] SharedLibrary  : libhello-jni.so[mips] Install        : libhello-jni.so => libs/mips/libhello-jni.so**** Build Finished ****
This process is actually the process of building native components and packaging them with Java applications. Now we can see a line of text on our mobile phone.


V. Introduction to the project structure and main directories


1. jni Directory: contains the source code of the native component and the Make file (Android. mk) that describes the native component build method. This directory serves as the build directory for the NDK build project.

2. libs Directory: contains the independent sub-directories of the specified target platform. This directory is included in the apk file during packaging.

3. obj Directory: This is an intermediate directory. The target files generated after the source code is compiled are stored in this directory. We 'd better not access this directory.

6. instance Engineering Analysis

The content of Android. mk is as follows:

# Copyright (C) 2009 The Android Open Source Project## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at##      http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.#LOCAL_PATH := $(call my-dir)include $(CLEAR_VARS)LOCAL_MODULE    := hello-jniLOCAL_SRC_FILES := hello-jni.cinclude $(BUILD_SHARED_LIBRARY)
For more information about Makefile, see my other blog post: http://blog.csdn.net/dawanganban/article/details/38750151.

Line 1: The Android. mk document must start with the definition of LOCAL_PATH variable, and my-dir is a macro definition of the system to define the directory location of the source file.

Row 2: the Android build system sets the CLEAR_VARS variable to the location of the clear-vars.mk fragment. For more makefile files of the fragment, see the ndk \ build \ core directory, as shown below:


The function is to clear the LOCAL _ <name> variable except LOCAL_PATH to avoid conflict.

Row 3: each native component is called a module. The LOCAL_MODULE variable is used to set a unique name for these modules.

Row 4: The LOCAL_SRC_FILES variable definition is used to create and assemble the source file list of this module, separated by spaces.

Line 5: Specifies the location where the build-shared-library.mk file is saved, which contains the necessary process to build the source file into a shared library.

Let's take a look at HelloJni. java

/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.example.hellojni;import android.app.Activity;import android.widget.TextView;import android.os.Bundle;public class HelloJni extends Activity{    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        /* Create a TextView and set its content.         * the text is retrieved by calling a native         * function.         */        TextView  tv = new TextView(this);        tv.setText( stringFromJNI() );        setContentView(tv);    }    /* A native method that is implemented by the     * 'hello-jni' native library, which is packaged     * with this application.     */    public native String  stringFromJNI();    /* This is another native method declaration that is *not*     * implemented by 'hello-jni'. This is simply to show that     * you can declare as many native methods in your Java code     * as you want, their implementation is searched in the     * currently loaded native libraries only the first time     * you call them.     *     * Trying to call this function will result in a     * java.lang.UnsatisfiedLinkError exception !     */    public native String  unimplementedStringFromJNI();    /* this is used to load the 'hello-jni' library on application     * startup. The library has already been unpacked into     * /data/data/com.example.hellojni/lib/libhello-jni.so at     * installation time by the package manager.     */    static {        System.loadLibrary("hello-jni");    }}
From the above we can see that the native stringFromJNI () method is called and the native keyword is used to notify the Java compiler. This is implemented in another language, add the Shared Library (static statement block) hello-jni to inform the virtual machine of the specific implementation of the native method. The java. lang. System class provides two static methods: load and loadLibrary. Let's take a look at the specific implementation.

#include <string.h>#include <jni.h>/* This is a trivial JNI example where we use a native method * to return a new VM String. See the corresponding Java source * file located at: * *   apps/samples/hello-jni/project/src/com/example/hellojni/HelloJni.java */jstringJava_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,                                                  jobject thiz ){#if defined(__arm__)  #if defined(__ARM_ARCH_7A__)    #if defined(__ARM_NEON__)      #if defined(__ARM_PCS_VFP)        #define ABI "armeabi-v7a/NEON (hard-float)"      #else        #define ABI "armeabi-v7a/NEON"      #endif    #else      #if defined(__ARM_PCS_VFP)        #define ABI "armeabi-v7a (hard-float)"      #else        #define ABI "armeabi-v7a"      #endif    #endif  #else   #define ABI "armeabi"  #endif#elif defined(__i386__)   #define ABI "x86"#elif defined(__x86_64__)   #define ABI "x86_64"#elif defined(__mips64)  /* mips64el-* toolchain defines __mips__ too */   #define ABI "mips64"#elif defined(__mips__)   #define ABI "mips"#elif defined(__aarch64__)   #define ABI "arm64-v8a"#else   #define ABI "unknown"#endif    return (*env)->NewStringUTF(env, "Hello from JNI !  Compiled with ABI " ABI ".");}
The first parameter JNIEnv is the interface pointer to the available JNI function table, and the second parameter jobject is the java object of the HelloJni class instance. The last line of code is to create a Java string for the UTF-8 with the c string.

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.