深刻理解Android(1)——理解Android中的JNI(上)

我參加了CSDN博客之星評選,若是在過去的一段時間裏陽光小強的博客對你有所幫助,在這裏但願能投上您寶貴的一票,天天均可以投一次:http://vote.blog.csdn.net/blogstar2014/details?username=lxq_xsyu#content
java

1、什麼是JNI

JNI是Java Native Interface的縮寫(Java本地調用),Java程序中的函數能夠調用Native語言寫的函數(通常指的是C/C++編寫的函數),Native語言寫的函數能夠調用Java層的函數。linux

2、爲何要有JNI

Java語言的跨平臺是由於在不一樣平臺上能夠運行Java虛擬機,而虛擬機是跑在具體平臺上的,而本質上Java是經過JNI技術實現的跨平臺,不少基層的模塊在Java語言誕生以前已經有了比較優秀的實現,爲了不重複造輪子因此咱們要使用JNI技術來使用已有的模塊。android


3、Mac OS上的環境搭建

在這裏說明一下Max OS上的所需環境搭建,Windows和Linux的請搜索相關資料。express

一、安裝JDK(此處省略)。apache

二、安裝ADT(Android Develop Tools),包括SDK和ADT插件,下載地址:http://pan.baidu.com/s/1o6OBIHG編程

三、安裝Xcode能夠去蘋果商店下載安裝(免費)。bash

四、安裝Apache ANT(下載地址:http://ant.apache.org/bindownload.cgi)詳細安裝過程能夠參考:http://blog.csdn.net/song_hui_xiang/article/details/14315529app

五、安裝GNU Make(默認已經安裝,因此不用安裝)可使用 make -version命令驗證是否安裝。less

六、安裝NDK(下載地址:http://pan.baidu.com/s/1i3l5L8T),解壓後在用戶根目錄下新建文件.bash_profile而後添加以下兩行(配置環境變量,能夠暫時不配置)。eclipse

export ANDROID_NDK_HOME=/Users/lixiaoqiang/Documents/install_tools/ndk/android-ndk-r10c
export PATH=${PATH}:${ANDROID_NDK_HOME}
注意:後面的地址是你解壓後的目錄

關於上面部分開發工具簡要介紹:

一、Apache Ant,是一個將軟件編譯、測試、部署等步驟聯繫在一塊兒加以自動化的一個工具,大多用於Java環境中的軟件開發。

二、NDK是Android原生開發工具包,能夠支持C/C++等原生編程語言開發Android應用,它提供頭文件、庫和交叉編譯工具鏈。

4、第一個示例程序

轉載請說明出處:http://blog.csdn.net/dawanganban

一、爲eclipse指定NDK路徑


二、導入Android NDK中的示例代碼(導入hello-jni工程),作過Android開發的朋友應該很熟悉,這裏就不囉嗦了。


三、向項目中添加原生支持

項目——>右擊——>Android Tools——>Add Native Support

該項目其實已經包含了一個原生項目,因此這一步能夠跳過,咱們直接Finish繼續。

四、插上手機(模擬器太慢了,建議使用真機)運行項目。在C/C++界面視圖咱們能夠看到以下信息

**** 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 ****
這個過程其實就是在構建原生組件並和Java應用程序打包的過程。此時在咱們手機上就能夠看到一行文字


5、項目結構及主要目錄介紹


一、jni目錄:包含原生組件的源代碼及描述原生組件構建方法的Make文件(Android.mk),該目錄做爲NDK構建項目時的構建目錄。

二、libs目錄:包含指定目標平臺的獨立子目錄,在打包時該目錄被包含在apk文件中。

三、obj目錄:這是一箇中間目錄,編譯源碼後產生的目標文件都保存在該目錄下,咱們最好不用訪問該目錄。

6、 實例工程解析

Android.mk的內容以下

# 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-jni
LOCAL_SRC_FILES := hello-jni.c

include $(BUILD_SHARED_LIBRARY)
有關Makefile的知識請參考個人另外一篇博文:http://blog.csdn.net/dawanganban/article/details/38750151

第一行:Android.mk文檔必須以LOCAL_PATH變量的定義開頭,my-dir是一個系統的宏定義,來定義源文件的目錄位置。

第二行:Android構建系統將CLEAR_VARS變量設置爲clear-vars.mk片斷的位置,更多片斷的makefile文件請看ndk\build\core目錄,以下:


做用是清除除了LOCAL_PATH之外的LOCAL_<name>變量,這樣能夠避免衝突。

第三行:每個原生組件被稱爲一個模塊,LOCAL_MODULE變量用來給這些模塊設定一個惟一的名稱。

第四行:LOCAL_SRC_FILES變量定義用來創建和組裝這個模塊的源文件列表,用空格隔開。

第五行:指明瞭build-shared-library.mk文件的保存位置,該片斷包含了將源文件構建成共享庫的必要過程。

下面咱們來看看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");
    }
}
從上面能夠看到調用了原生的stringFromJNI()方法,使用關鍵字native來通知Java編譯器,這個是用另外一種語言實現的,再經過加裝共享庫(static語句塊)hello-jni來告訴虛擬機原生方法的具體實現。java.lang.System類提供了兩個靜態方法,load和loadLibrary用來運行時加載共享庫。下面咱們來看看具體的實現。

#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
 */
jstring
Java_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 ".");
}
第一個參數JNIEnv是指向可用JNI函數表的接口指針,第二個參數jobject是HelloJni類實例的java對象。最後一句代碼是用c字符串建立UTF-8的Java字符串。
相關文章
相關標籤/搜索