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文件。

相关推荐
Lei活在当下1 天前
【项目踩坑实录】并发环境下,Glide缓存引起的图片加载异常
android·debug·glide
my_power5201 天前
检出git项目到android studio该如何配置
android·git·android studio
三少爷的鞋1 天前
Repository 方法设计:suspend 与 Flow 的决选择指南(以朋友圈为例)
android
阿里云云原生1 天前
Android App 崩溃排查指南:阿里云 RUM 如何让你快速从告警到定位根因?
android·java
cmdch20172 天前
手持机安卓新增推送按钮功能
android
攻城狮20152 天前
【rk3528/rk3518 android14 kernel-6.10 emcp sdk】
android
何妨呀~2 天前
mysql 8服务器实验
android·mysql·adb
QuantumLeap丶2 天前
《Flutter全栈开发实战指南:从零到高级》- 25 -性能优化
android·flutter·ios
木易 士心2 天前
MVC、MVP 与 MVVM:Android 架构演进之路
android·架构·mvc
猪在黑魔纹里2 天前
解决VSCode无法高亮、解析numpy中的部分接口(如pi、deg2rad)
ide·vscode·python·numpy