您的位置:首页 > 移动开发 > Android开发

android studio2.2初探ndk jni开发

2017-01-11 18:09 337 查看
android studio2.2以上ndk开发与之前有所不同,没有了那么多繁琐的生成什么.h 的过程。使用了CMake,初探门径,写了一个例子以作笔记。也希望能给一些在开发这条不归路上的同志们一些帮助,大神略过。

1.首先下载ndk



这也可以下载



2.ndk配置好后,创建项目



3.项目创建完成后,默认运行起来就会生成.so文件,会生成ndk需要的文件

(1)这里边是C 语言程序的逻辑部分, native-lib.cpp 文件名可自行修改



(2)externalNativeBuild —> cmake 编译好的文件, 显示支持的各种硬件等信息



(3)CMakeLists.txt —> CMake 脚本配置的文件



4.Gradle 文件会默认生成 配置 CMake



5 这是CMake

# Sets the minimum version of CMake required to build the native
# library. You should either keep the default value or only pass a
# value of 3.4.0 or lower.

cmake_minimum_required(VERSION 3.4.1)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds it for you.
# Gradle automatically packages shared libraries with your APK.

#CPP文件夹下带编译的cpp文件
add_library( # Sets the name of the library.
native-lib

# Sets the library as a shared library.
SHARED

# Provides a relative path to your source file(s).
# Associated headers in the same location as their source
# file are automatically included.
src/main/cpp/native-lib.cpp )

# Searches for a specified prebuilt library and stores the path as a
# variable. Because system libraries are included 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.

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 the
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
native-lib

# Links the target library to the log library
# included in the NDK.
${log-lib} )
#C++日志
find_library( log-lib log )

#target_link_libraries( native-lib $\{log-lib} )
target_link_libraries( native-lib $\{log-lib} lib_opencv)


英文不好的自行搜索一下含义

6.调用ndk的方法

(a). 使用 native 来定义 NDK 的方法:public native

(b). 使用 static 语块来引入 so 文件

(c). 调用时,只需要调用定义的 native 的方法即可

静态引入.so



ndk中的方法



直接调用就行

默认会有一个方法

7:C/C++ 语法部分

因为C/C++需要去了解



8: 生成的.so文件位置

想生成什么类型可以自己在build中添加



9:既然生成.so文件肯定不是只在本项目中使用,拷出.so文件

在你的新项目中新建一个jniLibs拷进去,为什么新建一个jniLibs是因为在build中有默认设置

sourceSets {
main {
jniLibs.srcDirs = ['src/main/jniLibs']
aidl.srcDirs = ['src/main/aidl']
}
}


你也可以修改到其他位置



怎么使用.so中的方法?

和在本项目中差不多,需要注意的是你的调用的这个类需要和生成的类包名保持一致,不然会找不到。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: