Deep understanding of Android (1)--understanding JNI in Android

Source: Internet
Author: User

I took part in the CSDN blog star selection, if in the past a period of time the Sun Cockroach's blog to help you, here hope to be able to cast your precious vote, every day can be cast once: http://vote.blog.csdn.net/blogstar2014/details ? username=lxq_xsyu#content

First, what is JNI

JNI is the abbreviation for Java Native interface (Java Local call), a function in a Java program can invoke a function written in the Native language (generally referred to as a function written by C/s + +), and a function that Native language writes can invoke the Java layer function.

Second, why should have JNI

The Java language cross-platform is because the Java Virtual machine can be run on different platforms, and the virtual machine is running on the concrete platform, but in essence Java is the cross-platform through the JNI technology, many grass-roots modules in the Java language before the birth of a relatively good implementation, To avoid making the wheel repeatedly, we use JNI technology to use the existing modules.


Third, the environment on MAC OS construction

Here is a description of the required environment on Max OS, Windows and Linux search for relevant information.

1. Install the JDK (omitted here).

2. Installing ADT (Android Develop Tools), including SDK and ADT plug-ins,: Http://pan.baidu.com/s/1o6OBIHG

3, install Xcode can go to the Apple Store download installation (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 do not install) you can use the make-version command to verify the installation.

6, install the NDK (: Http://pan.baidu.com/s/1i3l5L8T), after decompression in the user root directory to create new files. Bash_profile then add the following two lines (Configure environment variables, which can be temporarily not configured).

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 you unzipped

A brief introduction to the above-mentioned development tools:

1,Apache Ant, is a software compilation, testing, deployment and other steps to automate the process of a tool, mostly for the Java environment in software development.

2. NDK is an Android native development kit that supports native programming languages such as C + + to develop Android applications that provide header files, libraries, and cross-compilation toolchain.

Iv. the first sample program

Reprint please indicate source: Http://blog.csdn.net/dawanganban

1. Specify the NDK path for Eclipse


2. Import the sample code from Android NDK (import Hello-jni project), friends who have done Android development should be familiar with it.


3. Add native support to your project

Project-Right click-->android tools-->add Native Support

The project has actually included a native project, so this step can be skipped and we'll go straight to finish.

4, plug in the phone (the simulator is too slow, it is recommended to use the real machine) to run the project. We can see the following information in the C + + interface view

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 are larger than android:minsdkversion 3 in./A Ndroidmanifest.xml [arm64-v8a] Gdbserver: [aarch64-linux-android-4.9] libs/arm64-v8a/gdbserver[arm64-v8a] Gdbsetu P:LIBS/ARM64-V8A/GDB.SETUP[X86_64] Gdbserver: [x86_64-4.9] libs/x86_64/gdbserver[x86_64] Gdbsetup:li BS/X86_64/GDB.SETUP[MIPS64] Gdbserver: [mips64el-linux-android-4.9] libs/mips64/gdbserver[mips64] Gdbsetup:l IBS/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[a Rmeabi] gdbsetup:libs/armeabi/gdb.setup[x86] Gdbserver: [x86-4.6] libs/x86/gdbserver[x86] Gdbsetup:l Ibs/x86/gdb.setup[mips] Gdbserver:[mipsel-linux-android-4.6] libs/mips/gdbserver[mips] gdbsetup:libs/mips/gdb.setup[arm64-v8a] Compile:hell O-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[x 86_64] install:libhello-jni.so = libs/x86_64/libhello-jni.so[mips64] Compile:hello-jni <= hello-j NI.C[MIPS64] sharedlibrary:libhello-jni.so[mips64] install:libhello-jni.so = Libs/mips64/libhello-jni.so[a RMEABI-V7A] Compile thumb:hello-jni <= hello-jni.c[armeabi-v7a] sharedlibrary:libhello-jni.so[armeabi-v7a] Instal l:libhello-jni.so = Libs/armeabi-v7a/libhello-jni.so[armeabi] Compile thumb:hello-jni <= Hello-jni.c[ar Meabi] 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-j Ni.so[mips] Compile:hello-jni <= hello-jni.c[mips] sharedlibrary:libhello-jni.so[mips] Install:lib hello-jni.so = libs/mips/libhello-jni.so**** Build Finished * * * *
This process is essentially a process of building native components and packaging them with Java applications. Now we can see a line of text on our phone


V. Project structure and main catalogue introduction


1. JNI directory: Contains the source code of the native component and the make file (ANDROID.MK) that describes the native component building method, which is the build directory when the NDK builds the project.

2. Libs directory: A standalone subdirectory containing the specified target platform, which is included in the APK file when it is packaged.

3, obj directory: This is an intermediate directory, compiled source after the creation of the target files are stored in this directory, we do not need to access the directory.

Vi. Examples of engineering analysis

The contents of ANDROID.MK are as follows

# Copyright (C) The Android Open Source project## Licensed under the Apache License, Version 2.0 (the "License"); # yo U may not use this file except in compliance with the license.# your may obtain a copy of the License at## http://www.a      pache.org/licenses/license-2.0## unless required by applicable law or agreed to in writing, software# distributed under th E License is distributed on a "as is" basis,# without warranties OR CONDITIONS of any KIND, either express or implied.# S EE 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 Makefile's knowledge, please refer to my other blog post: http://blog.csdn.net/dawanganban/article/details/38750151

First line: The ANDROID.MK document must begin with the definition of the Local_path variable, My-dir is a system macro definition that defines the directory location of the source file.

The second line: The Android build system sets the Clear_vars variable to the location of the clear-vars.mk fragment, and more fragments of the makefile file see the Ndk\build\core directory, as follows:


The effect is to remove local_<name> variables other than Local_path, which avoids collisions.

Line three: Each native component is called a module, and the Local_module variable is used to set a unique name for these modules.

Line four: The local_src_files variable defines the list of source files used to create and assemble the module, separated by a space.

Line five: Indicates where to save the Build-shared-library.mk file, which contains the necessary procedures for building the source file into a shared library.

Now let's take a look at Hellojni.java.

/* Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License") ; * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by appli Cable law or agreed into writing, software * Distributed under the License is distributed on a "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 ;p ublic 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's implemented by the * ' hello-jni ' native library, which was packaged * with this app     Lication.    */Public native String Stringfromjni (); /* This is another native method declaration, that's *not* * implemented by ' Hello-jni '. This was simply to show that * you can declare as many native methods in your Java code * as you want, their implem     entation is searched in the * currently loaded native libraries only the first time * you are call them.     * * Trying to call this function would result in a * Java.lang.UnsatisfiedLinkError exception!    */Public native String Unimplementedstringfromjni (); /* 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 can be seen called the Native Stringfromjni () method, using the keyword native to inform the Java compiler, this is implemented in another language, and then by the addition of shared library (Static statement block) Hello-jni to tell the virtual machine native method of the specific implementation. The Java.lang.System class provides two static methods that load and LoadLibrary use to load a shared library at run time. Let's take a look at the specific implementation.

#include <string.h> #include <jni.h>/* 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/HELLOJN                                                  I.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 (__ar     M_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 "ARM eabi-v7a "#endif #endif #else #define ABI" Armeabi "#endif #elif defined (__i386__) #define ABI" x86 "#elif def ined (__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" u  Nknown "#endif return (*env)->newstringutf (env," Hello from JNI!) Compiled with Abi "Abi".);
The first parameter, JNIENV, is an 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 UTF-8 Java string with a C string.

Deep understanding of Android (1)--understanding JNI in Android

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.