DNK 学习小结

定义

JNI接口(Java Native Interface),它是Java平台的一个特性(并不是Android系统特有的)。



使用

一般情况下我们首先是将写好的C/C++代码编译成对应平台的动态库(windows一般是dll文件,linux一般是so文件等),这里我们是针对Android平台,所以只讨论so库。由于JNI编程支持C和C++编程,这里我们的栗子都是使用C++,对于C的版本可能会有些差异,但是主要的内容还是一致的,大家可以触类旁通。

使用

Android studio中使用NDK:




1、下载NDK开发工具
打开Project Structure,在SDK Location中的Android NDK Location下选择下载NDK

使用SDK Manager下载速度很慢,可以直接在 这里 下载后解压到SDK路径下的ndk-bundle文件夹下。或者指定其他路径。




2、工程的gradle.properties文件中添加

android.useDeprecatedNdk=true

在工程的local.properties文件下添加NDK路径:

ndk.dir=/Users/linwei/Library/Android/sdk/ndk-bundle

如果自己下载了NDK并解压到其他路径,此处要修改为其他路径。




3、 创建调用JNI的native方法:
创建文件,添加方法:

public class KeyHelper {

    static {
        System.loadLibrary("keylib");//加载so库名称与CMakeLists文件中add_library中声明的库名相同。
    }


    public native String stringKey();
}




4、 在main下创建jni文件夹并创建cpp文件:文件名与路径名与CMakeLists文件的add_library中指定的相同。

#include 
#include 

extern "C"
JNIEXPORT jstring

JNICALL
Java_com_lwcd_keylibrary_KeyHelper_stringKey(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "get key from C++: aaabbbbcccc";
    return env->NewStringUTF(hello.c_str());
}

注意方法名要根据native方法的文件路径以及方法名相同:包名(下划线代替点)+文件名+native方法名




5、 在Module的main文件夹下创建CMakeLists.txt文件
内容:

注意add_library中第一个参数为要创建的so库名称。第二个为创建的cpp源文件名称。

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

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 them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
             keylib

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             src/main/cpp/keyhelper.cpp )




6、在Module的 build.gradle中指定CMakeLists文件:

defaultConfig下添加:

externalNativeBuild {
            cmake {
                cppFlags "-frtti -fexceptions"
            }
        }

android下添加:

externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
DNK 学习小结_第1张图片
ndk_01.jpg





运行实例

通过KeyHelper调用stringKey方法

KeyHelper keyHelper = new KeyHelper();
        tv.setText(keyHelper.stringKey());

Summary:
这只是个使用的步骤,更多的原理还需要去研究。如果还不清楚的可以创建个新的工程在创建过程中勾选 include C++ support,之后工程会生成一个对应的使用NDK的Demo。

DNK 学习小结_第2张图片
ndk_02.jpg



Demo地址:

https://github.com/linwgithub/LWcdNDKMode

你可能感兴趣的:(DNK 学习小结)