Android studio 利用cmake编译和使用so文件

在Android Studio中使用CMake编译和使用.so文件,你需要执行以下步骤:

1.在CMakeLists.txt文件中指定你的.so文件。

2.在build.gradle文件中配置CMake构建脚本。

3.同步项目,让Gradle和CMake生成相应的Native库。

以下是一个简单的例子:

步骤1: 创建CMakeLists.txt

在你的项目的CMakeLists.txt文件中,添加你的.so文件。假设你的.so文件名为libexample.so,位于src/main/jniLibs/armeabi-v7a/目录下:

cmake_minimum_required(VERSION 3.4.1)

add_library( lib_example SHARED IMPORTED )

set_target_properties( lib_example

PROPERTIES IMPORTED_LOCATION

${CMAKE_SOURCE_DIR}/src/main/jniLibs/armeabi-v7a/libexample.so )

add_executable( your_app_name main.cpp )

target_link_libraries( your_app_name

lib_example )

步骤2: 配置build.gradle

在你的build.gradle文件中,确保你有以下配置:

android {

...

defaultConfig {

...

ndk {

// Specifies the ABI configurations of your native

// libraries Gradle should build and package with your APK.

abiFilters 'armeabi-v7a', 'x86'

}

}

externalNativeBuild {

cmake {

path "CMakeLists.txt"

}

}

...

}

dependencies {

...

}

tasks.withType(JavaCompile) {

compileTask -> compileTask.dependsOn 'ndkBuild'

}

tasks.withType(JavaCompile) {

compileTask -> compileTask.dependsOn 'ndkBuild'

}

task ndkBuild(type: Exec, description: 'Compile JNI source via NDK') {

commandLine "$projectDir/../ndk-build",

'-C', file('src/main').absolutePath,

'all', 'NDK_DEBUG=1'

}

步骤3: 同步项目

在Android Studio中,点击Tools -> Android -> Sync Project with Gradle Files,让Gradle和CMake根据你的配置生成相应的构建文件和库文件。

完成这些步骤后,CMake会编译你的.so文件,并且在应用构建过程中将其打包到APK中。在Java代码中,你可以使用System.loadLibrary("example")来加载这个.so文件。

相关推荐
程序员陆业聪1 小时前
Compose Strong Skipping Mode 的真相:它并不会让你的类型变 Stable
android
摇滚侠4 小时前
IDEA 生成 try catch 快捷键
java·ide·intellij-idea
Tiger Z4 小时前
Positron 教程1 --- 用户界面
ide·编程·positron
shaoming37765 小时前
浏览器动作开发:地址栏图标点击事件、弹出页面设计
android·mysql·adb
赏金术士6 小时前
Kotlin 协程与挂起函数(Coroutines & suspend)入门到实战
android·开发语言·kotlin
泡泡以安8 小时前
Unidbg学习笔记(十三):固定随机干扰项
android·逆向
泡泡以安8 小时前
Unidbg学习笔记(十六):Console Debugger
android·逆向
赏金术士8 小时前
Room + Flow 完整教程(现代 Android 官方方案)
android·kotlin·room·compose
泡泡以安8 小时前
Unidbg学习笔记(八):文件系统层补环境
android·逆向
泡泡以安8 小时前
Unidbg学习笔记(六):补环境的思维框架
android·逆向