天天看點

Android NDK入門之Hello Jni

FBI Warning:歡迎轉載,但請标明出處:http://blog.csdn.net/codezjx/article/details/8876379,未經本人同意請勿用于商業用途,感謝支援!

參考文章:http://www.cnblogs.com/hibraincol/archive/2011/05/30/2063847.html

其中有一些改動,Windows環境下結合Cygwin+Eclipse自動編譯.so庫并打包至apk

前言:為何要用到NDK?

概括來說主要分為以下幾種情況:

1. 代碼的保護,由于apk的java層代碼很容易被反編譯,而C/C++庫反彙難度較大。

2. 在NDK中調用第三方C/C++庫,因為大部分的開源庫都是用C/C++代碼編寫的。

3. 便于移植,用C/C++寫得庫可以友善在其他的嵌入式平台上再次使用。

下面就介紹下Android NDK的入門學習過程:

入門的最好辦法就是學習Android自帶的例子, 這裡就通過學習Android的NDK自帶的demo程式:Hello-jni來達到這個目的。

一、 開發環境的搭建

android的NDK開發需要在linux下進行: 因為需要把C/C++編寫的代碼生成能在arm上運作的.so檔案,這就需要用到交叉編譯環境,而交叉編譯需要在linux系統下才能完成。若您是Windows的忠實使用者,不想用Linux系統,也不想裝虛拟機,那麼我隆重向您推薦Cygwin,他是一個在windows平台上運作的unix模拟環境。具體環境搭建可以參考我的這篇帖:http://blog.csdn.net/codezjx/article/details/8858825

二、 代碼的編寫

1. 首先是寫java代碼

建立一個Android應用工程HelloJni,建立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");
    }
}
           

這段代碼很簡單,注釋也很清晰,這裡隻提兩點:

static {
        System.loadLibrary("hello-jni");
    }
           

表明程式開始運作的時候會加載hello-jni, static區聲明的代碼會先于onCreate方法執行。如果你的程式中有多個類,而且如果HelloJni這個類不是你應用程式的入口,那麼hello-jni(完整的名字是libhello-jni.so)這個庫會在第一次使用HelloJni這個類的時候加載。

public native String  stringFromJNI();

public native String  unimplementedStringFromJNI();
           

可以看到這兩個方法的聲明中有 native 關鍵字, 這個關鍵字表示這兩個方法是本地方法,也就是說這兩個方法是通過本地代碼(C/C++)實作的,在java代碼中僅僅是聲明。

2. 編寫相應的C/C++代碼

剛開始學的時候,有個問題會讓人很困惑,相應的C/C++代碼如何編寫,函數名如何定義? 這裡講一個方法,利用javah這個工具生成相應的.h檔案,然後根據這個.h檔案編寫相應的C/C++代碼。

2.1 生成相應.h檔案:(使用javah工具生成)

用法:javah [選項] <類>

其中 [選項] 包括:

        -help                 輸出此幫助消息并退出

        -classpath <路徑>     用于裝入類的路徑

        -bootclasspath <路徑> 用于裝入引導類的路徑

        -d <目錄>             輸出目錄

        -o <檔案>             輸出檔案(隻能使用 -d 或 -o 中的一個)

        -jni                  生成 JNI樣式的頭檔案(預設)

        -version              輸出版本資訊

        -verbose              啟用詳細輸出

        -force                始終寫入輸出檔案

使用全限定名稱指定 <類>(例如,java.lang.Object)。

指令行下輸入:

cd C:\Users\Administrator\Desktop\Android_Projects_Floder\hello-jni  //進入hello-jni根目錄

javah -classpath bin\classes -d jni com.example.hellojni.HelloJni           //在jni目錄下生成頭檔案

參數說明:

-classpath bin\classes:表示類的路勁

-d jni :表示生成的頭檔案存放的目錄

com.example.hellojni.HelloJni :則是完整類名

這一步的成功要建立在已經在 bin/com/example/hellojni/  目錄下生成了 HelloJni.class的基礎之上。

現在可以看到jni目錄下多了個com_example_hellojni_HelloJni.h檔案:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_example_hellojni_HelloJni */

#ifndef _Included_com_example_hellojni_HelloJni
#define _Included_com_example_hellojni_HelloJni
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_example_hellojni_HelloJni
 * Method:    stringFromJNI
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_stringFromJNI
  (JNIEnv *, jobject);

/*
 * Class:     com_example_hellojni_HelloJni
 * Method:    unimplementedStringFromJNI
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_unimplementedStringFromJNI
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif
           

上面代碼中的JNIEXPORT 和 JNICALL 是jni的宏,在android的jni中不需要,當然寫上去也不會有錯。

從上面的源碼中可以看出這個函數名那是相當的長啊。。。。 不過還是很有規律的, 完全按照:Java_pacakege_class_mathod 形式來命名。

也就是說:Hellojni.java中 stringFromJNI() 方法對應于 C/C++中的 Java_com_example_hellojni_HelloJni_stringFromJNI() 方法。

注意下其中的注釋:

Signature: ()Ljava/lang/String;

()表示函數的參數為空(這裡為空是指除了JNIEnv *, jobject 這兩個參數之外沒有其他參數,JNIEnv*, jobject是所有jni函數必有的兩個參數,分别表示jni環境和對應的java類(或對象)本身),

Ljava/lang/String; 表示函數的傳回值是java的String對象。

2.2 編寫相應的hello-jni.c檔案:

/*
 * 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.
 *
 */
#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 )
{
    return (*env)->NewStringUTF(env, "Hello from JNI from bear !");
}
           

這裡隻是實作了Java_com_example_hellojni_HelloJni_stringFromJNI方法,而 Java_com_example_hellojni_HelloJni_unimplementedStringFromJNI 方法并沒有實作,因為在HelloJni.java中隻調用了stringFromJNI()方法,是以unimplementedStringFromJNI()方法沒有實作也沒關系,不過建議最好還是把所有java中定義的本地方法都實作了,寫個空函數也行啊。。。有總比沒有好。

Java_com_example_hellojni_HelloJni_stringFromJNI() 函數隻是簡單的傳回了一個内容為 "Hello from JNI !" 的jstring對象(對應于java中的String對象)。

hello-jni.c檔案已經編寫好了,現在可以把com_example_hellojni_HelloJni.h檔案給删了,當然留着也行,隻是我還是習慣把不需要的檔案給清理幹淨了。

3. 編譯hello-jni.c 生成相應的庫

3.1 編寫Android.mk檔案

在jni目錄下(即hello-jni.c 同級目錄下)建立一個Android.mk檔案,Android.mk 檔案是Android 的 makefile檔案,内容如下:

# 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)
           

LOCAL_PATH := $(call my-dir)

一個Android.mk 檔案首先必須定義好LOCAL_PATH變量。它用于在開發樹中查找源檔案。在這個例子中,宏函數’my-dir’, 由編譯系統提供,用于傳回目前路徑(即包含Android.mk file檔案的目錄)。

include $( CLEAR_VARS)

CLEAR_VARS由編譯系統提供,指定讓GNU MAKEFILE為你清除許多LOCAL_XXX變量(例如 LOCAL_MODULE, LOCAL_SRC_FILES, LOCAL_STATIC_LIBRARIES, 等等...), 

除LOCAL_PATH 。這是必要的,因為所有的編譯控制檔案都在同一個GNU MAKE執行環境中,所有的變量都是全局的。

LOCAL_MODULE := hello-jni

編譯的目标對象,LOCAL_MODULE變量必須定義,以辨別你在Android.mk檔案中描述的每個子產品。名稱必須是唯一的,而且不包含任何空格。

注意:編譯系統會自動産生合适的字首和字尾,換句話說,一個被命名為'hello-jni'的共享庫子產品,将會生成'libhello-jni.so'檔案。

重要注意事項:

如果你把庫命名為‘libhello-jni’,編譯系統将不會添加任何的lib字首,也會生成 'libhello-jni.so',這是為了支援來源于Android平台的源代碼的Android.mk檔案,如果你确實需要這麼做的話。

LOCAL_SRC_FILES := hello-jni.c

LOCAL_SRC_FILES變量必須包含将要編譯打包進子產品中的C或C++源代碼檔案。注意,你不用在這裡列出頭檔案和包含檔案,因為編譯系統将會自動為你找出依賴型的檔案;僅僅列出直接傳遞給編譯器的源代碼檔案就好。

注意,預設的C++源碼檔案的擴充名是’.cpp’. 指定一個不同的擴充名也是可能的,隻要定義LOCAL_DEFAULT_CPP_EXTENSION變量,不要忘記開始的小圓點(也就是’.cxx’,而不是’cxx’)

include $(BUILD_SHARED_LIBRARY)

BUILD_SHARED_LIBRARY表示編譯生成共享庫,是編譯系統提供的變量,指向一個GNU Makefile腳本,負責收集自從上次調用'include $(CLEAR_VARS)'以來,定義在LOCAL_XXX變量中的所有資訊,并且決定編譯什麼,如何正确地去做。還有 BUILD_STATIC_LIBRARY變量表示生成靜态庫:lib$(LOCAL_MODULE).a, BUILD_EXECUTABLE 表示生成可執行檔案。

3. 在eclipse重新編譯HelloJni工程,生成apk(若在前面已經配置好Cygwin環境,會自動編譯打包) 

eclipse中重新整理下HelloJni工程,重新編譯生成apk,libhello-jni.so共享庫會一起打包在apk檔案内。

在模拟器中看看運作結果:

Android NDK入門之Hello Jni