Android for JNI (vi)--cross-compiling, NDK overview and file structure, writing your own first JNI project

Source: Internet
Author: User

Android for JNI (vi)--cross-compiling, NDK overview and file structure, writing your own first JNI project

Finally back to our Android, we have to configure this NDK environment, but before we have to understand the basic terminology

I. Cross-compilation
    • Compile a binary program that can be executed by another platform under one platform
    • CPU platform: ARM X86 MIPS (instruction Set)
    • System platform: Windows Linux Mac
    • Principle: Simulate the characteristics of another platform to compile the program
      • Source--precompiled-------------The executable program
    • Toolchain: One tool uses the automatic call to the next
Two. JNI Common tools
    • Ndk:native Developer Kits
    • cdt:c/c++ Developer Tools (plugin/highlight C keyword)
    • Linux Simulator under Cygwin:windows (Rom series is spoken)
Three. NDK Configuration

ndk::http://wear.techbrood.com/tools/sdk/ndk/

Background of 1.NDK generation

The Android platform has supported C and C + + development since its inception. As we all know, the Android SDK is based on Java implementations, which means that third-party apps that are developed based on the Android SDK must use the Java language. But this is not the same as "third-party apps can only use Java." When the Android SDK was first released, Google announced that its virtual machine Dalvik supported JNI programming, which means that third-party applications could call their own C dynamic library through JNI, i.e., on Android, the "java+c" programming is always possible.

However, Google also said that the use of Native SDK programming compared to the Dalvik virtual machine has some disadvantages, the Android SDK documentation, no JNI help found. Even if third-party application developers use JNI to complete their own C dynamic-link library (SO) development, how so is packaged with the app as an APK and released? There are also technical barriers in this. For example, the program is more complex, compatibility is difficult to protect, unable to access the framework api,debug more difficult and so on. Developers need to use them at their own discretion.

So the NDK was born. The NDK full name is native development Kit.

The release of the NDK enabled the development of "Java+c" to become officially supported by the official development approach. The NDK will be the beginning of the Android platform to support c development.

2. Why use the NDK
    • 1. 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. The existing open Source library is easy to use. Most of the existing open source libraries are written in C + + code.

    • 3. Improve the efficiency of the execution of procedures. 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.

3.NDK Introduction
    • 1.NDK is a collection of a range of tools

The NDK provides a range of tools to help developers quickly develop C (or C + +) dynamic libraries and automatically package so and Java applications together as APK. These tools are great for developers.

The NDK integrates the cross compiler and provides the corresponding MK file isolation CPU, platform, ABI and other differences, developers simply need to modify the Mk file (stating "which files need to compile", "compilation characteristics Requirements", etc.), you can create a so.

The NDK can automatically package so with Java applications, greatly reducing the developer's packaging effort.

    • 2.NDK provides a stable, feature-limited API header file declaration

Google expressly declares that the API is stable and supports the currently published API in all subsequent releases. As seen from this version of the NDK, these APIs support a very limited number of features, including: C standard library (LIBC), Standard math Library (LIBM), compression library (LIBZ), log Library (Liblog).

Let's download and install the NDK first!

4.NDK directory Structure

When we download it, we unzip it directly.

Let's analyze it.

    • Docs: Help Documentation
    • Build/tools:linux Batch processing files
    • Platforms: Storage of the H-header files and so-class libraries used by JNI
    • prebuilt: Pre-compiled tools for use
    • Samples: small Example
    • SOURCES:NDK part of the source code
    • Toolchains: Tool Chain

    • Ndk-build.cmd: Compiling and Packaging C code

In fact, the SDK is similar, we will not elaborate

Four. Hellojni

To create our own first JNI project, we created a new project in Eclipse,--hellojni, and asked why I didn't use Android studio, this ... is not very skilled, because the work needs, has been using eclipse, Look at the example under the NDK's folder we know, first of all, we're going to create a jni directory, we're creating a new

We create a new Class C, again, before we take a look at which hello-jni in the API example of how C program is written

/* Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "Licen Se "); * 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. * */#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/HELLOJN I.java * *Jstringjava_com_example_hellojni_hellojni_stringfromjni (jnienv* env, job Ject 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".");}

Here, in front of the note, no tube, we look at the last return, we write a C file in the JNI directory

#include <stdio.h>#include <stdlib.h>#include <jni.h>/** * 计算相加 * 定义一个本地函数 * env:结构体二级指针,该结构体封装了大量的函数指针,方便我们开发某些功能 * thiz:本地方法调用者的对象,这里值MainActvity的对象 */jstring Java_com_lgl_hellojni_MainActivity_HelloJNI(JNIEnv* env, jobject thiz) {    "hello jni";    //把C字符串转换成java字符串    /**     * 官方文档:return (*env)->NewStringUTF(env, "Hello from JNI !  Compiled with ABI " ABI ".");     */    jstring jstr = (*env)->NewStringUTF(env,cstr);    return jstr;}

After writing, we are useless to run, we need to manually compile the

We go into our source file directory, open cmd, Input ndk-build.cmd to compile, he will report an error, because of the path, we are missing a Mk file, to create this file, we need to review the android-mk.html document, we create a new android.mk file in the JNI directory, the words copied in

LOCAL_PATH := $(call my-dir)include $(CLEAR_VARS)LOCAL_MODULE    := hello_jni   //生成的文件名LOCAL_SRC_FILES := hello_jni.c   //要编译的文件include $(BUILD_SHARED_LIBRARY)

Now, we can compile, after compiling, there will be a dynamic link library under the Libs directory.

This is the library we're doing.

Of course, we still need to load the dynamic link library, we go back to mainactivity

    static{        //模块名字        System.loadLibrary("hello-jni");    }

And then we can use the

Toast.makeText(this, HelloJNI(), Toast.LENGTH_LONG).show();

But here to run the words need arm platform, you are useless on the X86 platform, the article said before, if you compile faint difficulty, that is related to the configuration is not well, recommended here

Http://www.cnblogs.com/skyseraph/p/3979238.html
Configuration environment Baidu a lot of

Demo Download: http://download.csdn.net/detail/qq_26787115/9501088

Android for JNI (vi)--cross-compiling, NDK overview and file structure, writing your own first JNI project

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.