1. 程式人生 > >Android Studio 簡單生成so檔案並呼叫

Android Studio 簡單生成so檔案並呼叫

第1步:新建一個Android Studio 工程 JniHelloWorld。新建一個MyJni.java檔案。
這裡寫圖片描述

MyJni.java

public class MyJni {

    static {
        System.loadLibrary("MyJni");
    }

    public native static String getString();
}

第2步:然後點選一下 make project 會在app的build目錄下面生成.class檔案。
這裡寫圖片描述

第3步,在app/src/main資料夾下新建一個jni資料夾,然後開啟Android Studio的終端,cd到這個目錄,然後輸入下面的指令

javah -jni -classpath D:\github\JniHelloWorld\app\build\intermediates\classes\debug com.brotherd.jnihelloworld.MyJni

就會在這個jni資料夾下生成一個.h檔案,com_brotherd_jnihelloworld_MyJni.h,檔案內容如下。

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_brotherd_jnihelloworld_MyJni */
#ifndef _Included_com_brotherd_jnihelloworld_MyJni #define _Included_com_brotherd_jnihelloworld_MyJni #ifdef __cplusplus extern "C" { #endif /* * Class: com_brotherd_jnihelloworld_MyJni * Method: getString * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_com_brotherd_jnihelloworld_MyJni_getString (JNIEnv *, jclass); #ifdef __cplusplus
} #endif #endif

在jni目錄下新建一個c/c++source file ,取名test.c 實現上面.h檔案中的方法。

#include "jni.h"
#include "com_brotherd_jnihelloworld_MyJni.h"

JNIEXPORT jstring JNICALL Java_com_brotherd_jnihelloworld_MyJni_getString
  (JNIEnv *env, jclass jz){

  return (*env)->NewStringUTF(env,"this is the first time for me to use jni");

  }

接著在jni資料夾下新建Android.mk和Application.mk檔案。
Android.mk

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

LOCAL_MODULE := MyJni
LOCAL_SRC_FILES := Test.c
include $(BUILD_SHARED_LIBRARY)

Application.mk

APP_ABI := all

第4步,關聯下載好的ndk包,我的解壓好的路徑是C:\android-ndk-r14b
這裡寫圖片描述

然後在終端進入到jni目錄,輸入指令 ndk-build,就會生成相應的so檔案。

這裡寫圖片描述

第5步,呼叫so檔案。
在app的bulid檔案中加入如下程式碼,然後build project

android {
    ...
    sourceSets {
        main() {
            jniLibs.srcDirs = ['src/main/libs']
            jni.srcDirs = [] //遮蔽掉預設的jni編譯生成過程
        }
    }
}

在MainActivity中呼叫

public class MainActivity extends AppCompatActivity {

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.textView);
        textView.setText(MyJni.getString());
    }
}

執行效果圖

這裡寫圖片描述

結尾:現在對JNI還是一竅不通,有時間再看看,先記錄一下。