android ndk初步1

來源:互聯網
上載者:User
一直嫌ndk麻煩,不過不用ndk也是很悲劇的。

網上看了別人做的,東拼西湊的,ndk跟jni還是有點區別的,ndk中的簡單一些了,打住,開始了。ndk r7不用cyg也可以了,公司不上上qq,好不容易放個假,也懶得進linux折騰了,在Windows上qq,順便搞點東東。

  ndk怎麼弄不說了。下載解壓。配置一下環境變數,ndk-build出現問題的可能用linux或者安裝cygwin,刪除ndk下面的prebuild就行了。awk有衝突

 

首先建立一個這個,你懂的,不要弄sample的東東,你不知道是怎麼來的。最好一步一步來。1package com.example.hellojni;import android.app.Activity;import android.os.Bundle;import android.widget.Toast;public class HelloJni extends Activity {/** * @author ThinkinBunny Called when the activity is first created. */public native String stringFromJNI();public native int resultRet(int x, int y);//這是添加的 求和,呵呵,c我忘得差不多了,惡補中/* * 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");}@Overridepublic void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        System.out.println(resultRet(3, 4));        Toast.makeText(getApplicationContext(),                stringFromJNI() + "|" + resultRet(3, 4), 1).show();    }}

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

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代碼中僅僅是聲明。

用eclipse編譯該工程,產生相應的.class檔案,這步必須在下一步之前完成,因為產生.h檔案需要用到相應的.class檔案。

然後 cd 到這個項目的src下面 

PS E:\workspace\HelloJni\src> javah -jni com.example.hellojni.HelloJni

網上說javah -classpath bin -d jni com.example.hellojni.HelloJni  
,可是我的一直是錯誤: 找不到 'com.example.hellojni.HelloJni' 的類檔案。

至於很多人說在bin下面,我是一直失敗,什麼原因我沒搞清楚,上班問問同事。

 

繼續,。好了,在項目 目錄new 一個 jni檔案夾 。目錄結構應該是這樣的:AndroidManifest.xml  assets  bin  default.properties  gen  res  src

好了,

javah -jni com.example.hellojni.HelloJni

  運行完重新整理一下你的目錄,把com_example_hellojni_HelloJni。h 拖進 jni,好像這個檔案沒啥用也

我們來看看com_example_hellojni_HelloJni.h的內容:

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 __cplusplusextern "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:    resultRet * Signature: (II)I */JNIEXPORT jint JNICALL Java_com_example_hellojni_HelloJni_resultRet  (JNIEnv *, jobject, jint, jint);/* * 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 形式來命名。

也就是說:

Hello.java中 stringFromJNI() 方法對應於 C/C++中的 Java_com_example_hellojni_HelloJni_stringFromJNI() 方法

HelloJni.java中的 unimplementedStringFromJNI() 方法對應於 C/C++中的 Java_com_example_hellojni_HelloJni_unimplementedStringFromJNI() 方法

注意下其中的注釋:

Signature: ()Ljava/lang/String;

()Ljava/lang/String;

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

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

 

2.2 編寫相應的.c檔案:

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 */jstringJava_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,                                                  jobject thiz ){    return (*env)->NewStringUTF(env, "Hello from JNI !");}jint Java_com_example_hellojni_HelloJni_resultRet  (JNIEnv * env, jobject thiz, jint a, jint b){  jint x=0;  x=a+b; return x;  }

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

 

編寫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-jniLOCAL_SRC_FILES := hello-jni.cinclude $(BUILD_SHARED_LIBRARY)
這個Androd.mk檔案很短,下面我們來逐行解釋下:

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 表示產生可執行檔。

 

  cd   workspace\HelloJni 到下面  然後 ndk-build

PS E:\workspace\HelloJni> ndk-build
"Compile thumb : hello-jni <= hello-jni.c
SharedLibrary  : libhello-jni.so
Install        : libhello-jni.so => libs/armeabi/libhello-jni.so

在eclipse重新編譯HelloJni工程,產生apk

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

嘿嘿,jni首測 sun上面有,下個研究下

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.