下載Mac OS X版本的NDK
在android官網(wǎng)NDK頁(yè)面可以看到相關(guān)信息,可以戳這里,進(jìn)入這個(gè)頁(yè)面可以看見(jiàn)下載版本分為兩個(gè),一個(gè)為32-bit,一個(gè)為64-bit,到底怎么看,可以再終端輸入uname -v,如果出現(xiàn)RELEASE_X86_64,表示為64-bit,如果不清楚,可以戳這里
準(zhǔn)備JNI
- 新建一個(gè)AndroidApplication Project,命名為HelloNDK,并在其工程根目錄下手動(dòng)建一個(gè)jni目錄,在其目錄下創(chuàng)建一個(gè)Android.mk編譯配置文件和hello-ndk.c源文件。
Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := hello-ndk
LOCAL_SRC_FILES := hello-ndk.c
include $(BUILD_SHARED_LIBRARY)
hello-ndk.c
#include <string.h>
#include <jni.h>
jstring Java_com_example_HelloNDK_MyActivity_stringFromJNI(JNIEnv* env, jobject thiz)
{
return (*env)->NewStringUTF(env, "Hello from JNI!");
}
在這里jsstring后面Jave_com_example_HelloNDK(這個(gè)是包名),stringFromJNI是方法名
- 編譯文件將下載NDK包解壓到指定位置,將路徑加入到.bash_profile(或者使用zsh為.zshrc),到project的jni目錄下,使用命令ndk-build,如果成功會(huì)出現(xiàn)以下文字
[armeabi] Compile thumb : hello-ndk <= hello-ndk.c
[armeabi] SharedLibrary : libhello-ndk.so
[armeabi] Install : libhello-ndk.so => libs/armeabi/libhello-ndk.so
在java文件中引用JNI
MyActivity.java
package com.example.HelloNDK;//包名
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setText(stringFromJNI());
setContentView(textView);
}
public native String stringFromJNI();
public native String unimplementedStringFromJNI();
static {
System.loadLibrary("hello-ndk");
}
}
注意:Java代碼中使用native關(guān)鍵字標(biāo)示方法是JNI庫(kù)中的函數(shù),雖然上一步編譯出來(lái)的JNI庫(kù)的名字是libhello-ndk.so,但是按照規(guī)范,System.loadLibrary中的參數(shù)是去掉lib和.so的。