Android studio 4.x在已有项目中集成jni

很久没有写jni相关的项目了,闲下来复习以下,把jni项目的构建流程记录以下,为以后使用方便查阅。

1. 环境配置

1. 下载NDK

方法一:在官网手动下载
image.png

选择想要下载的对应系统NDK版本,下载完成之后,解压到你ndk存放目录,这个目录后续配置环境变量需要用到

方法二:使用Android studio SDK Manager下载(Android studio 4.x)

点击Android studio 工具栏的

image.png
图标或者根据路径 File | Settings | Appearance & Behavior | System Settings | Android SDK或者Tool|SDK Manager打开SDK Manager 界面
image.png

选择SDK Tools 条目,勾选NDK和CMake后点击apply按钮等待下载完即刻
image.png

下载完成之后,ndk的位置在你的Android sdk目录下方,有一个ndk的文件夹。

2. 配置NDK

1.配置环境变量

打开高级环境变量控制

image.png

配置环境变量,在环境变量的Path中添加ndk的路径
image.png

我的路径是D:\Android\SDK\ndk\21.3.6528147
image.png

在cmd中输入ndk-build 出现以下结果证明配置成功
image.png

2.已有项目中集成jni

1. 在Androidstudio中配置

打开已有项目,通过File|Project Structure|SDK location打开SDK和NDK配置界面,然后在ndk中配置你刚刚下载的NDK路径

image.png

2. 在项目app目录下的build.gradle文件进行配置

apply plugin: 'com.android.application'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.1"

    defaultConfig {
        applicationId "com.marlon.testjni"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        // 增加cmake控制属性
        externalNativeBuild {
            cmake {
                // 指定编译架构 可以省略
                abiFilters 'arm64-v8a', 'armeabi-v7a', 'x86', 'x86_64'
                // cpp 编译时的额外选项 可以省略
                cppFlags ""
            }
        }
    }

    // 在android节点下
    // 指定CMakeLists.txt路径
    externalNativeBuild {
        cmake {
            // 在该文件种设置所要编写的c源码位置,以及编译后so文件的名字
            path "src/main/jni/CMakeLists.txt"
            // cmake版本 可以省略
            version "3.10.2"
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

}

2. 新建JNI folder用来放置C/C++文件和CMakeLists文件

image.png

在app/src/main目录下将会创建一个jni文件夹。

3. 新建HelloJNI文件

在src/main/java文件夹下面创建HelloJNI.java文件

package com.marlon.testjni;

/**
 * @author by marlon
 * @date on 2020/9/13.
 */

public class HelloJNI {

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

    public static native String helloJNI();

}

4.创建native-lib文件

src/main/java 目录下创建native-lib.cpp

//
// Created by marlon on 2020/9/13.
//
#include 

extern "C"
JNIEXPORT jstring JNICALL
Java_com_marlon_testjni_HelloJNI_helloJNI(JNIEnv *env, jclass clazz) {
    // TODO: implement helloJNI()
    return env->NewStringUTF("Hello From JNI!");
}

5. 创建CMakeLists文件

在src/main/jni文件中创建

# 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构建本地库时所需的最小版本
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.
            #将资源文件生成动态链接库(so文件)的库名称(文件名称:“lib" +设置的名称)
             native-lib

             # Sets the library as a shared library.

             SHARED

             # Provides a relative path to your source file(s).
             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.
                       #将所有的add_library中的库链接起来,有多少个add_library成的库就将其添加到这里
                       #这个和add_library中的指定的so库名称一致
                       native-lib

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

3.使用

package com.marlon.testjni;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

        findViewById(R.id.text).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //在这里直接调用
                String string = HelloJNI.helloJNI();
                Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

整个就是这样

你可能感兴趣的:(Android studio 4.x在已有项目中集成jni)