Android NDK开发(五)JNI和NDK

今天先说一下JNI和NDK的概念,然后在记录一下CMake开发的步骤和注意事项

概念

JNI:Java Native Interface标准是Java平台的一部分,JNI是Java语言提供的让Java语言和其他语言(尤其是C/C++)进行沟通,Java语言通过JNI可以调用C/C++代码,C/C++代码也可以通过JNI调动Java代码
NDK:Native Development Kit是一系列工具的集合,它提供了一系列的工具,帮助开发者快速开发C/C++动态库,并且自动将so库和Java打包成APK文件
两者关系:NDK可以为我们生成C/C++动态链接库,JNI是Java和C/C++沟通的桥梁,两者之间没有关系,只因为Android是由Java语言开发的,所以需要使用JNI。

NDK开发的好处

其实学习过C/C++的同学都知道,真的一辈子都不想再去碰到这个语言,好用是好用,但是真的不喜欢,各种设计都是反人类的。但是他也有自己的优点,比如更加方便管理内容等

  1. 项目可以调用底层的一些C/C++的东西,而我们的Java语言是无法直接访问到系统底层内容的。大部分的开源库都是有C/C++语言编写的,这样也方便与我们理解
  2. 为了更加高效的效率,将要求高性能的逻辑使用C/C++代码来实现,从而提供应用程序的执行效率,但是需要注意,虽然C/C++的运行没有问题,但是Java和C/C++的交流就是非常大的开销
  3. 基于安全性考虑,防止被反编译。使用C/C++来写程序中比较重要的部分,然后打包成so库
  4. 便于移植,用C/C++写的依赖库可以在其他平台上快速集成。

配置

使用Android studio作为开发工具,那么在开发工具中就有很多方式让我们进行NDK开发,先说第一个,CMake。

下载安装NDK

下载地址
根据自己的实际情况下在相应的NDK版本
将下载好之后的NDK解压到一个文件夹中。

如果不想自己动手去下载,可以通过Android studio下载。打开Android Studio中的File->Setting,在Setting中找到Appearence&Behavior。选择子目录System settings。在选择Android SDK,在右侧中选择SDK Tools,在复选空中选择对应的CMake,LLDB和NDK。那么这样子NDK的环境就配置好了。

当NDK下载好之后,可以将环境变量进行修改。这里如何将NDK添加到环境变量中,我就不做介绍。

创建项目

点击新建一个项目

在新建项目页面一定要电击伤C++支持,这样就会默认使用CMake,可以帮我们省了很多事情。
这里写图片描述
其他的选择项默认即可
之后会在有一个选择框,如下
这里写图片描述

  • 这里第一个下拉选框中的内容,表示的是进行C++编写时候所注意的平台,因为C++也是一种在发展,那么有不同的版本,执行的操作和标准库也是有很多的区别的。这里,我们使用默认的方式就是表明使用CMake的方式。
  • 希望启用对C++异常处理的支持,选中此复选框。如果启用复选框,Android studio会将-fexceptions标志添加到模块级build.gradle文件的cppFlags中,Gradle也会传递个CMake。
  • 如果写昂支持RTTI,请选中复选框,如果启用复选框,Android studio会将frtti标志添加到模块机build.gradle文件的cppFlags中,Gradle将会传递个CMake。
    最后两个默认不选即可。那么点击OK,完成项目的创建
    项目的目录结构如下所示
    这里写图片描述

这里面有两个文件需要注意,一个是native-lib.cpp文件,这个文件表示的是进行沟通的操作,这里我们可以直接在cpp文件中写C++代码,第二个就是CMakeLists.txt文件,这个文件用来声明当前so库的个数和引入的方式。

我们可以看到在native-lib.cpp文件中,我们声明了一个方法叫做Java_com_niupule_ndk_1demo_MainActivity_stringFromJNI,然后我们需要对这个方法的返回值进行规定,具体代码如下所示

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

extern "C" JNIEXPORT jstring

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

在MainActivity中需要使用我们的C++代码,那么他的主要代码是

package com.niupule.ndk_demo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method
        TextView tv = (TextView) findViewById(R.id.sample_text);
        tv.setText(stringFromJNI());
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
}

CMakeLists.txt的内容是

# 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.
             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 )

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries 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 this
# 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++代码直接按照之前的样式去执行即可

对CMakeLists.txt文件的分析

在CMakeLists.txt文件中内容较多,下面对CMakeLists的内容进行分析

cmake_minimum_required(VERSION 3.4.1)

表示设置构建本机库文件所需的CMake的最小版本

add_library( demo-lib
                    SHARED
                    src/main/cpp/demo-lib.cpp )

添加自己写的C/C++源文件

find_library( log-lib
                    log )

依赖NDK中的库

target_link_libraries( demo-lib
                                ${log-lib} )

将目标库于NDK中的库进行连接。

配置build.gradle文件

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.niupule.ndk_demo"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0-rc01'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

有很大的一个缺点,每次我们创建一个新的C文件都必须要在CMakeLists中声明一次。添加的时候,就是直接添加一个add_library的方式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值