基于Android studio3.6的JNI教程之helloworld思路詳解
jdk環境變量配置:
path中增加下面2個路徑,也就是android studio的路徑,android有自帶的jdk。
E:AndroidAndroid StudiojrebinE:AndroidAndroid Studiobin
新建工程:
一定要選擇Native c++類型,最后要選c++11支持。
SDK設置:
File->Settings
File->Project Structure
首先確定工程的目錄結構,然后嘗試運行一下工程,使用模擬器,確保工程沒問題,
在MainActivity的同級目錄,新建一個hello.java,然后做一個簡單的實現,
package com.example.myapplication; public class hello { public native int add(int i, int j);}
使用android studio自帶的Terminal進入該hello.java所在目錄,執行,
javac hello.java
Terminal下回到app/src/main所在目錄,執行,
javah -d jni -classpath ./java com.example.myapplication.hello
此時,會在main目錄下面生成一個和cpp,java同級的目錄jni。
在該目錄結構里面新建hello.cpp。
將com_example_myapplication_hello.h中的內容復制進hello.cpp中,并且進行方法的實現,
#include <jni.h>/* Header for class com_example_myapplication_hello */ #ifndef _Included_com_example_myapplication_hello#define _Included_com_example_myapplication_hello#ifdef __cplusplusextern 'C' {#endif/* * Class: com_example_myapplication_hello * Method: add * Signature: (II)I */ #include 'com_example_myapplication_hello.h' JNIEXPORT jint JNICALL Java_com_example_myapplication_hello_add (JNIEnv *, jobject, jint i, jint j){return i+j;} #ifdef __cplusplus}#endif#endif
將com_example_myapplication_hello.h,hello.cpp這連個文件復制到cpp所在的目錄,
然后修改CMakeLists.txt,增加,
add_library( # Sets the name of the library. hello # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). hello.cpp )
修改target_link_libraries如下,
target_link_libraries( # Specifies the target library. native-lib hello # Links the target library to the log library # included in the NDK. ${log-lib} )
修改hello.java的調用方式,
package com.example.myapplication; public class hello { static { System.loadLibrary('hello'); } public native int add(int i, int j);}
修改MainActivity.java中的onCreate函數,
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Example of a call to a native method TextView tv = findViewById(R.id.sample_text); //tv.setText(stringFromJNI()); tv.setText('hello 9+10= ' + new hello().add(9, 10)); }
然后,rebuild project,沒有錯誤后,然后run app。
最終程序整體目錄結構,以及運行效果,
JNI的整體流程思路:
Java先定義一個類,類中定義一個需要c++來實現的方法.通過javah生成需要c++實現的.h的c++頭文件實現.h的c++頭文件中定義的方法Cmake編譯運行
總結
到此這篇關于基于Android studio3.6的JNI教程之helloworld思路詳解的文章就介紹到這了,更多相關android studio JNI helloworld內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: