JNI 開發步驟
-
創建 Java 類,編寫 native 方法
public class HelloJNI { public native String getContentFromJni(); }
-
Terminal 中切換到項目的 src/main/java 目錄下,使用 javah 命令生成 jni 頭文件
E:\AndroidProject\ProgressAndroid\app\src\main\java>javah com.xing.progressandroid.jni.HelloJNI
-
在項目 app 目錄右鍵 new -> Folder -> JNI folder 創建 C 或 C++ 目錄,AndroidStudio 會生成一個 jni 目錄,將 jni 頭文件複製到 jni 目錄中
-
在 jni 目錄中創建與頭文件同名的 C 或 C++ 源文件,實現 jni 頭文件中聲明的函數
#include "com_xing_progressandroid_jni_HelloJNI.h" JNIEXPORT jstring JNICALL Java_com_xing_progressandroid_jni_HelloJNI_getContentFromJni (JNIEnv *env, jclass jclz) { return env->NewStringUTF("I'm from C++"); }
-
在項目的 app 目錄下創建 CMakeLists.txt 文件,編寫內容:
# cmake 最低版本 cmake_minimum_required(VERSION 3.4.1) add_library( # Sets the name of the library. # 設置生成的 so 動態庫名字 helloJni # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). # 生成 so 文件的 C/C++ 文件 src/main/jni/com_xing_progressandroid_jni_HelloJNI.cpp) find_library( # Sets the name of the path variable. log-lib # Specifies the name of the NDK library that # you want CMake to locate. log) target_link_libraries( # Specifies the target library. helloJni # Links the target library to the log library # included in the NDK. ${log-lib})
-
在 build.gradle 文件中引用 CMakeLists.txt 文件
android { defaultConfig { ndk { abiFilters "armeabi-v7a", "x86" //設置生成的 so 支持的 cpu 類型 } } ....... externalNativeBuild { cmake { path "CMakeLists.txt" } } }
-
make 編譯工程,生成 so 文件
-
加載 so 文件
public class JniTestActivity extends AppCompatActivity {
static {
System.loadLibrary("helloJni"); // so 文件名和 CMakeLists.txt 中指定的名字一致
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jni_test);
TextView textView = findViewById(R.id.tv_jni);
HelloJNI helloJNI = new HelloJNI();
textView.setText(helloJNI.getContentFromJni());
}
}