一, 介绍
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视频。