相信很多同學都是之前習慣了在eclipse 上開發。而且關於jni 的開發也是在eclipse上集成,那麼如何在androidstudo 上開發jni 呢。我廢話不多說馬上上乾貨
第一步 下載ndk 點擊打開鏈接
下載完畢後請在file - project structure -AndroidNdkLocation 配置下載完畢的ndk路徑 最好版本在13以上低版本會有問題。
第二步 新建一個項目 新建一個jni 工具類 Myjni裏面寫好你要使用的方法
public class MyJni {
static {
System.loadLibrary("mybase");
}
public static native String sayHello();
}
第三步 在terminal 下執行javah命令 生成頭文件
執行命令後 會在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使用 並運行 大功告成