深入理解Android(1)——理解Android中的JNI,androidjni

來源:互聯網
上載者:User

深入理解Android(1)——理解Android中的JNI,androidjni

我參加了CSDN部落格之星評選,如果在過去的一段時間裡陽光小強的部落格對你有所協助,在這裡希望能投上您寶貴的一票,每天都可以投一次:http://vote.blog.csdn.net/blogstar2014/details?username=lxq_xsyu#content

一、什麼是JNI

JNI是Java Native Interface的縮寫(Java本地調用),Java程式中的函數可以調用Native語言寫的函數(一般指的是C/C++編寫的函數),Native語言寫的函數可以調用Java層的函數。

二、為什麼要有JNI

Java語言的跨平台是因為在不同平台上可以運行Java虛擬機器,而虛擬機器是跑在具體平台上的,而本質上Java是通過JNI技術實現的跨平台,很多基層的模組在Java語言誕生之前已經有了比較優秀的實現,為了避免重複造輪子所以我們要使用JNI技術來使用已有的模組。


三、Mac OS上的環境搭建

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

1、安裝JDK(此處省略)。

2、安裝ADT(Android Develop Tools),包括SDK和ADT外掛程式,:http://pan.baidu.com/s/1o6OBIHG

3、安裝Xcode可以去蘋果商店下載安裝(免費)。

4、安裝Apache ANT(:http://ant.apache.org/bindownload.cgi)詳細安裝過程可以參考:http://blog.csdn.net/song_hui_xiang/article/details/14315529

5、安裝GNU Make(預設已經安裝,所以不用安裝)可以使用 make -version命令驗證是否安裝。

6、安裝NDK(:http://pan.baidu.com/s/1i3l5L8T),解壓後在使用者根目錄下建立檔案.bash_profile然後添加如下兩行(配置環境變數,可以暫時不配置)。

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

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

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

2、NDK是Android原生開發套件,可以支援C/C++等原生程式設計語言開發Android應用,它提供標頭檔、庫和交叉編譯工具鏈。

四、第一個樣本程式

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

1、為eclipse指定NDK路徑


2、匯入Android NDK中的範例程式碼(匯入hello-jni工程),做過Android開發的朋友應該很熟悉,這裡就不囉嗦了。


3、向項目中添加原生支援

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

該項目其實已經包含了一個原生項目,所以這一步可以跳過,我們直接Finish繼續。

4、插上手機(模擬器太慢了,建議使用真機)運行項目。在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應用程式打包的過程。此時在我們手機上就可以看到一行文字


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


1、jni目錄:包含原生組件的原始碼及描述原生組件構建方法的Make檔案(Android.mk),該目錄作為NDK構建項目時的構建目錄。

2、libs目錄:包含指定目標平台的獨立子目錄,在打包時該目錄被包含在apk檔案中。

3、obj目錄:這是一個中間目錄,編譯源碼後產生的目標檔案都儲存在該目錄下,我們最好不用訪問該目錄。

六、 執行個體工程解析

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-jniLOCAL_SRC_FILES := hello-jni.cinclude $(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 */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 ".");}
第一個參數JNIEnv是指向可用JNI函數表的介面指標,第二個參數jobject是HelloJni類執行個體的java對象。最後一句代碼是用c字串建立UTF-8的Java字串。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.