Android

Android JNI初识 HelloWorld

2018-09-20  本文已影响54人  潇风寒月

以前学过一点JNI,很久没用,然后又忘了,复习一下.

一.NDK是什么

原生开发工具包 (NDK) 是一组可让您在 Android 应用中利用 C 和 C++ 代码的工具。 可用以从您自己的源代码构建,或者利用现有的预构建库

NDK使用场景

NDK会不可避免的增加开发过程的复杂性,通常是不建议使用的.

二.JNI

从设备获取卓越性能以用于计算密集型应用,例如游戏或物理模拟。
重复使用您自己或其他开发者的 C 或 C++ 库。

三.引入NDK

  1. 新建项目,勾选include C++ support,一路next,finish.
  2. 完成.

完成上述步骤就已经配置好了NDK,我们来看看比一般的项目多了哪些东西.

image

1. cpp文件夹

很明显,这里面是存放cpp源文件的.

#include <jni.h>
#include <string>

//这里的jstring表示的是返回值,对应于Java中的String
extern "C" JNIEXPORT jstring

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

public native String stringFromC();

Java和Jni的类型对照表

image

引用类型对照表

image

2. CMakeLists.txt

多了个txt文件,看看里面都有啥东西


# cmake版本
cmake_minimum_required(VERSION 3.4.1)

add_library( # Sets the name of the library. lib的名称
             native-lib

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).  源文件
             src/main/cpp/native-lib.cpp )

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 )

target_link_libraries( # Specifies the target library.
                       native-lib

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )

  1. cmake_minimum_required cmake版本
  2. add_library 指定要编译的库,并将所有的 .c 或 .cpp 文件包含指定。
  3. find_library 查找库所在目录
  4. target_link_libraries 将库与其他库相关联

3. build.gradle

android {
    defaultConfig {
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

使用cmake配置gradle关联.

4. java代码

static {
    System.loadLibrary("native-lib");
}

public native String stringFromJNI();
  1. 在应用启动的时候加载native-lib
  2. 声明native()方法.
上一篇下一篇

猜你喜欢

热点阅读