AndroidStuio之Jni開發基礎篇
阿新 • • 發佈:2019-02-12
相信很多同學都是之前習慣了在eclipse 上開發。而且關於jni 的開發也是在eclipse上整合,那麼如何在androidstudo 上開發jni 呢。我廢話不多說馬上上乾貨
下載完畢後請在file - project structure -AndroidNdkLocation 配置下載完畢的ndk路徑 最好版本在13以上低版本會有問題。
第二步 新建一個專案 新建一個jni 工具類 Myjni裡面寫好你要使用的方法
第三步 在terminal 下執行javah命令 生成標頭檔案public class MyJni { static { System.loadLibrary("mybase"); } public static native String sayHello(); }
執行命令後 會在java 包的根目錄下生成一個com_nh_cp_test_MyJni.h 這個標頭檔案
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class com_nh_cp_test_MyJni */ #ifndef _Included_com_nh_cp_test_MyJni #define _Included_com_nh_cp_test_MyJni #ifdef __cplusplus extern "C" { #endif /* * Class: com_nh_cp_test_MyJni * Method: sayHello * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_com_nh_cp_test_MyJni_sayHello (JNIEnv *, jclass); #ifdef __cplusplus } #endif #endif
第四步 在main下新建一個jni 資料夾 然後在jni資料夾裡新建一個c 檔案 隨便起名字 我這裡新建了一個 my.c 我們吧上面的程式碼考進來 然後 只要修改 JniCall Java_com_nh_cp_text_myJni_sayHello 這個 方法即可 其他都不同動 ,不會c 的同學請自行補充c 的知識
// // Created by ouyangyu on 2017-04-13 . // /* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class com_nh_cp_test_MyJni */ #ifndef _Included_com_nh_cp_test_MyJni #define _Included_com_nh_cp_test_MyJni #ifdef __cplusplus extern "C" { #endif /* * Class: com_nh_cp_test_MyJni * Method: sayHello * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_com_nh_cp_test_MyJni_sayHello (JNIEnv *env, jclass obj){ return (*env)->NewStringUTF(env,"JNI hahahahahahahaha"); } #ifdef __cplusplus } #endif #endif
第五步 然後配置gradle 在build.gradle 中配置 so 的架構 及so 的名字
第六步 點選綠色小錘子 makeProject 生成so 檔案 在你的 buil- - intermedtated -- ndk--lib 下會生成so 檔案 然後在 main 下新建一個jniLib 吧 so檔案 複製到這個資料夾裡
第七步 在需要的地方呼叫MyJni.sayhello使用 並執行 大功告成