深入理解Android(1)——理解Android中(zhōng)的JNI(上) - 新聞資(zī)訊 - 雲南小程序開發|雲南軟件開發|雲南網站(zhàn)建設-西山區知普網絡科技工作室

159-8711-8523

雲南網建設/小程序開發/軟件開發

知識

不管是網站(zhàn),軟件還是小程序,都要直接或間接能為您産生價值,我們在追求其視覺表現的同時,更側重于功能的便捷,營銷的便利,運營的高效,讓網站(zhàn)成為營銷工具,讓軟件能切實提升企業(yè)内部管理水平和(hé)效率。優秀的程序為後期升級提供便捷的支持!

您當前位置>首頁 » 新聞資(zī)訊 » 技術(shù)分享 >

深入理解Android(1)——理解Android中(zhōng)的JNI(上)

發表時間:2020-10-19

發布人:葵宇科技

浏覽次數:32


我參加了CSDN博客之星評選,如(rú)不雅在以前的一段時光裡陽光小強的博客對你(nǐ)有所贊助,在這裡欲望能投上您寶貴的一票,天天都可(kě)以投一次:http://vote.blog.csdn.net/blogstar2014/details?username=lxq_xsyu#content

一、什麼是JNI


JNI是Java Native Interface的縮寫(Java本地調用),Java法度榜樣中(zhōng)的函數可(kě)聲調用Native說話寫的函數(一般指的是C/C++編寫的函數),Native說話寫的函數可(kě)聲調用Java層的函數。

二、為什麼要有JNI


Java說話的跨平台是因為在不合平台上可(kě)以運行Java虛拟機,而虛拟機是跑在具體平滔喔贍,而本質上Java是經由過程JNI技巧實現的跨平台,很多基層的模塊在Java說話出生之前已經有了比較優良的實現,為了避免反複造輪子(zǐ)所以我們要應用JNI技巧來應用已有的模塊。
[img]http://img.blog.csdn.net/20150104210435843?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZGF3YW5nYW5iYW4=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center

三、Mac OS上的情況搭建


在這裡解釋一下(xià)Max OS上的所需情況搭建,Windows和(hé)Linux的請搜刮相幹材料。
1、安裝JDK(此處省略)。
2、安裝ADT(Android Develop Tools),包含SDK和(hé)ADT插件,下(xià)載地址:http://pan.baidu.com/s/1o6OBIHG
3、安裝Xcode可(kě)以去蘋不雅市廛下(xià)載安裝(免費)。
4、安裝Apache ANT(下(xià)載地址:http://ant.apache.org/bindownload.cgi)具體安裝過程可(kě)以參考:http://blog.csdn.net/song_hui_xiang/article/details/14315529
5、安裝GNU Make(默認已經安裝,所以不消安裝)可(kě)以應用 make -version敕令驗證是否安裝。
6、安裝NDK(下(xià)載地址:http://pan.baidu.com/s/1i3l5L8T),解壓後在用戶根目次下(xià)新建文(wén)件.bash_profile然後添加如(rú)下(xià)兩行(設備情況變量,可(kě)以臨時不設備)。
export ANDROID_NDK_HOME=/Users/lixiaoqiang/Documents/install_tools/ndk/android-ndk-r10c
export PATH=${PATH}:${ANDROID_NDK_HOME}
留意:後面的地址是你(nǐ)解壓後的目次
關(guān)于膳绫擎部分開辟對象扼要介紹:
1、Apache Ant,是一個(gè)将軟件編譯、測試、安排等步調聯系袈溱一路(lù)加以主動(dòng)化的一個(gè)對象,大年夜多用于Java情況中(zhōng)的軟件開辟。
2、NDK是Android原生開辟對象包,可(kě)以支撐C/C++等原生編程說話開辟Android應用,它供給頭文(wén)件、庫和(hé)交叉編譯對象鍊。

四、第一個(gè)示例法度榜樣


轉載請解釋出處:http://blog.csdn.net/dawanganban
1、為eclipse指定NDK路(lù)徑
[img]http://img.blog.csdn.net/20150104212549675?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZGF3YW5nYW5iYW4=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
2、導入Android NDK中(zhōng)的示例代碼(導入hello-jni工程),做過Android開辟的同夥應當很熟悉,這裡就不煩瑣了。
[img]http://img.blog.csdn.net/20150104212738236?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZGF3YW5nYW5iYW4=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
3、向項目中(zhōng)添加原生支撐
項目——>右擊——>Android Tools——>Add Native Support
該項目其實已經包含了一個(gè)原生項目,所以這一步可(kě)以跳過,我們直接Finish持續。
4、插上手機(模仿器(qì)太慢了,建議應用真機)運行項目。在C/C++界面視圖我們可(kě)以看到如(rú)下(xià)信息
**** 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 ****
這個(gè)過程其實就是在構建原生組件并和(hé)Java應用法度榜樣打包的過程。此時在我們手機上就可(kě)以看到一行文(wén)字
[img]http://img.blog.csdn.net/20150104220026008?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZGF3YW5nYW5iYW4=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center

五、項目構造及重要目次介紹


[img]http://img.blog.csdn.net/20150104220319324?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZGF3YW5nYW5iYW4=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
1、jni目次:包含原生組件的源代碼及描述原生組件構建辦法的Make文(wén)件(Android.mk),該目次作為NDK構建項目時的構建目次。
2、libs目次:包含指定目标平台的自力子(zǐ)目次,在打包時該目次被包含在apk文(wén)件中(zhōng)。
3、obj目次:這是一個(gè)中(zhōng)心目次,編譯源碼後産生的目标文(wén)件都保存在該目次下(xià),我們最好不消拜訪該目次。

六、 實例工程解析


Android.mk的内容如(rú)下(xià)
# 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)
有關(guān)Makefile的常識請參考我的另一篇博文(wén):http://blog.csdn.net/dawanganban/article/details/38750151
第一行:Android.mk文(wén)檔必須以LOCAL_PATH變量的定義開首,my-dir是一個(gè)體系的宏定義,來定義源文(wén)件的目次地位。
第二行:Android構建體系将CLEAR_VARS變量設置為clear-vars.mk片段的地位,更多片段的makefile文(wén)件請看ndk\build\core目次,如(rú)下(xià):
[img]http://img.blog.csdn.net/20150104222306062?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZGF3YW5nYW5iYW4=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
感化是清除除了LOCAL_PATH以外的LOCAL_<name>變量,如(rú)許可(kě)以避免沖突。
第三行:每一個(gè)原生組件被稱為一個(gè)模塊,LOCAL_MODULE變量用來給這些模塊設定一個(gè)獨一的名稱。
第四行:LOCAL_SRC_FILES變量定義用來建立和(hé)組裝這個(gè)模塊的源文(wén)件列表,用空格隔開。
第五行:指清楚明了build-shared-library.mk文(wén)件的保存地位,該片段包含了将源文(wén)件構建成共享庫的須要過程。
下(xià)面我們來看看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");
    }
}
大年夜膳绫擎可(kě)以看到調用了原生的stringFromJNI()辦法,應用關(guān)鍵字native來通(tōng)知Java編譯器(qì),這個(gè)是用另一種說話實現的,再經由過程加裝共享庫(static語句塊)hello-jni來告訴虛拟機原生辦法的具體實現。java.lang.System類供給了兩個(gè)靜态辦法,load和(hé)loadLibrary用來運行時加載共享庫。下(xià)面我們來看看具體的實現。
#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 ".");
}
第一個(gè)參數JNIEnv是指向可(kě)用JNI函數表的接口指針,第二個(gè)參數jobject是HelloJni類實例的java對象。最後一句代碼是用c字符串創建UTF-8的Java字符串。

相關(guān)案例查看更多