一, 介紹
NDK: 就是工具,是可以在android 跟C++交互的工具集
JNI :可以看做是規範,C/C++與Java交互的方法(協議)
二,先配置下環境
本文環境:AndroidStudio3.6.3
NDK,下如圖:
弄完了之後,新建項目:如圖選擇C++項目
C++版本選擇,這個默認就行,
目錄如下
目錄介紹:
1,native-lib.cpp就是我們要寫C語言的地方,在編譯完成之後會生成一個so包。
2,CMakeList.txt:可以理解爲Cpp文件統一管理的配置清單
3,AS默認把JNI文件夾,去掉了直接在MainAtivity中實現了。
public class MainActivity extends AppCompatActivity {
// Used to load the 'native-lib' library on application startup.
//翻譯:用於在應用程序啓動時加載“本機-lib”庫。
static {
System.loadLibrary("native-lib");
}
@Override
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());
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
* 一個由“native-lib”本機庫實現的本機方法,
* 與此應用程序打包在一起。
*/
public native String stringFromJNI();
}
上面的環境就搭建完畢了
三,CMakeLists.txt文件
這個文件,默認的樣子
我們需要做的只是在裏面添加自己想要的配置。
add_library( # Sets the name of the library. todo:設置庫的名稱。 這個名字可以隨便起,
上面的MainActivity 中靜態代碼塊中加載的lib 就是他 ,只不過我這裏改成了Hello
Hello
# Sets the library as a shared library.todo:將庫設置爲共享庫。
SHARED
# Provides a relative path to your source file(s).todo:提供到源文件的相對路徑。
Hello.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. todo:指定目標庫。 連接目標庫。
Hello
# Links the target library to the log library
# included in the NDK.
${log-lib} )
編譯通過後,會在如圖目錄產生一個so文件,我們加載的就是這個so
默認的會在名字前面加lib這個我們不用管。
多個so包或者多個Cpp文件要怎麼辦
add_library(),多加幾個。
參考文章在此
視頻+文章學習,
還有看的尚硅谷高級android視頻。