前端安卓工程-JNI调试调用底层检测识别库
程序员文章站
2022-06-12 19:49:49
...
作者:DayInAI 日期:20190128
一、CmakeLists
1、原始CmakeLists
#----------------指定 库文件名字(.so)和c++文件路径(可多个)
add_library( # Sets the name of the library.
hello-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
src/main/cpp/hello-lib.cpp}
)
# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.
#--------------依赖NDK中的库
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 )
# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.
#--------------关联log库到本地库。如果你本地的库(native-lib)想要调用log库的方法,
#那么就需要配置这个属性
target_link_libraries( # Specifies the target library.
hello-lib
# Links the target library to the log library
# included in the NDK.
${log-lib} )
2、填写工程模板
#----------------指定 库文件名字(.so)和c++文件路径(可多个)
add_library(
hello-lib
SHARED
src/main/cpp/hello-lib.cpp}
)
#--------------依赖NDK中的库
find_library(
log-lib
log )
#--------------关联log库到本地库。如果你本地的库(native-lib)想要调用log库的方法,
#那么就需要配置这个属性
target_link_libraries(
hello-lib
${log-lib} )
3、配置库文件
add_library( # Sets the name of the library.
hello-lib
SHARED
src/main/cpp/hello-lib.cpp
src/main/cpp/test.cpp
)
4、添加源文件
aux_source_directory(src/main/cpp SRC_LIST)
add_library(
hello-lib
SHARED
${SRC_LIST}
二、JNI生成并调用.so动态库
1、实现步骤
1、编写 Java 代码。我们将从编写 Java 类开始,这些类执行三个任务:声明将要调用的本机方法;装入包含本机代码的共享库;然后调用该本机方法。
2、编译 Java 代码。在使用 Java 类之前,必须成功地将它们编译成字节码。
3、创建 C/C++ 头文件。C/C++ 头文件将声明想要调用的本机函数说明。
4、编写 C/C++ 代码。这一步实现 C 或 C++ 源代码文件中的函数。C/C++ 源文件必须包含步骤 3 中创建的头文件。
5、创建共享库文件。从步骤 4 中创建的 C 源代码文件来创建共享库文件。
6、运行 Java 程序。运行该代码,并查看它是否有用。
2、在Java中调用JNI
package com.wwj.jni;
import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
public class TestJNIActivity extends Activity {
private TextView textView;
static { // 加载动态库
System.loadLibrary("TestJNI");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textview);
TestJNI testJNI = new TestJNI(); // 调用native方法
boolean init = testJNI.Init();
if (init == true) { // 调用Add函数
int sum = testJNI.Add(100, 150);
textView.setText("你真是个" + sum);
} else {
textView.setText("你比二百五还要二百五");
}
testJNI.Destory();
}
}