android studio里gradle3.0以上实现jni调用

gradle3.0以上进行jni调用的时候和之前的版本会略有不同

首先第一步:

首先新建一个工程, 我的工程目录如下:

 

我本地使用的gradle版本:

 

app的build.gradle内容如下所示:

android {
apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.jni.jnidemo5"
        minSdkVersion 26
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

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

以上就是新建的工程的基本设置, 接下来就是正式开始:

首先在包下新建一个JNINative.java的类用于写native方法

package com.jni.jnidemo5;

public class JNINative {

    public native String getString();
}

很简单只有一个获取字符串的方法.

使用javah生成对应的.h文件

具体方法如下:

打开Android Studio的Terminal(控制台)

输入: cd app/src/main/java

输入: javah com.jni.jnidemo5.JNINative

会在工程的 app/src/main/java/下生成对应的.h文件

生成的.h文件内容如下:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_jni_jnidemo5_JNINative */

#ifndef _Included_com_jni_jnidemo5_JNINative
#define _Included_com_jni_jnidemo5_JNINative
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_jni_jnidemo5_JNINative
 * Method:    getString
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_jni_jnidemo5_JNINative_getString
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

编写对应的C文件

在src上右键新建一个jni目录, 目录结构如下

 

 

在jni目录下右键 新建一个hellotest.c文件

文件的内容如下(根据生成的.h文件修改而成):

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_jni_jnidemo5_JNINative */

#ifndef _Included_com_jni_jnidemo5_JNINative
#define _Included_com_jni_jnidemo5_JNINative
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_jni_jnidemo5_JNINative
 * Method:    getString
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_jni_jnidemo5_JNINative_getString
  (JNIEnv *env, jclass jobject){
 return (*env)->NewStringUTF(env,"hello world from c!!!");
  }
#ifdef __cplusplus
}
#endif
#endif

注意这里修改的内容:

配置NDK环境

点击project structure 设置工程的ndk目录

接下来是和低版本的gradle不一致的地方了, 因为gradle3.0以上useDeprecatedNdk这个东西不推荐使用了, 也就是我们不需要在gradle.properties里添加android.useDeprecatedNdk=true这句话了

如果我们还使用这个东东, studio就会提示我们:

Error:Execution failed for task ':app:compileDebugNdk'. > Error: Flag android.useDeprecatedNdk is no longer supported and will be removed in the next version of Android Studio. Please switch to a supported build system.Consider using CMake or ndk-build integration.

推荐我们使用CMake, 这里我就选择CMake方式

CMake方式实现编译so文件

  1. 打开SDK Manager

勾选箭头指向的两个插件, 安装

 

2.在app的build.gradle里的deaultConfig节点里添加如下代码:

externalNativeBuild {
    cmake {
        cppFlags ""
        //生成多个版本的so文件
        abiFilters 'arm64-v8a','armeabi-v7a','x86','x86_64'
    }
}

如下图所示:

 3.在android节点里添加如下代码

externalNativeBuild {
    cmake {
        path "CMakeLists.txt"  // 该文件配置了c源码位置,以及编译后so文件的名字

    }
}

如下图所示

4.在和app里的build.gradle的同级目录里新建一个名为CMakeLists.txt的文件, 并copy如下代码

# 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.
#CMakeLists.txt
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文件名称.
       hello

       # Sets the library as a shared library.
       SHARED
       # 设置这个so文件为共享.

       # Provides a relative path to your source file(s).
       # 设置我们的c/c++文件路径, 注意文件名要和我们的c文件相同
       src/main/jni/hellotest.c)

# 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.
            # 制定目标库.注意要和上面的so文件名称一致
            hello

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

注意自己要修改里面带注释的地方, 主要是c文件名和编译后的so的文件名

5.然后Build工程我们就能看到编译成功的so库文件了, 如下所是:

6.Copy生成的so文件到lib目录下:

 

7.修改MainActivity里的代码让我们的程序跑起来

package com.jni.jnidemo5;

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

public class MainActivity extends AppCompatActivity {

    private TextView tv;

    static {
        System.loadLibrary("hello");
    }

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

        tv = findViewById(R.id.tv);

        tv.setText(new JNINative().getString());

    }
}

点击run运行结果如下:

demo下载地址:

https://github.com/githubStudy/jnidemo

猜你喜欢

转载自blog.csdn.net/c1392851600/article/details/84030314