通过https://blog.csdn.net/qq_15255121/article/details/115244956这篇文章我们可以很快地创建ndk工程。
今天我们讲一讲如何在先用的工程中加入ndk。
1、我们创建一个module ----yuannative(这一步非必须,可以在app模块直接添加)
2、我们写CMakeList
cmake_minimum_required(VERSION 3.10.2)
add_library( # Specifies 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.c)
# Specifies a path to native header files.
include_directories(src/main/cpp/include/)
find_library( # Defines the name of the path variable that stores the
# location of the NDK library.
log-lib
# Specifies the name of the NDK library that
# CMake needs to locate.
log )
add_library( app-glue
STATIC
${ANDROID_NDK}/sources/android/native_app_glue/android_native_app_glue.c )
# Links your native library against one or more other native libraries.
target_link_libraries( native-lib app-glue ${log-lib} )
具体含义参考https://developer.android.google.cn/studio/projects/configure-cmake
3、通过
add_library( # Specifies 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.c)
# Specifies a path to native header files.
include_directories(src/main/cpp/include/)
我们要在src/main/cpp下新建native-lib.c. 和 include文件夹
4、修改module下build.gradle
plugins {
id 'com.android.library'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
minSdkVersion 19
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles "consumer-rules.pro"
externalNativeBuild {
cmake {
cppFlags "-std=c++11"
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
version "3.10.2"
}
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.material:material:1.1.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
这里面添加了
externalNativeBuild { cmake { cppFlags "-std=c++11" } }
和
externalNativeBuild { cmake { path "CMakeLists.txt" version "3.10.2" } }
4、添加.c与.h的代码
//
// Created by yuanxuzhen on 7/16/21.
//
#include <jni.h>
#include "native-lib.h"
JNIEXPORT jstring JNICALL
Java_com_yuanxuzhen_yuannative_TestNative_getName(JNIEnv *env, jclass clazz) {
// TODO: implement urlProtocolInfo()
LOGE("Java_com_yuanxuzhen_yuannative_TestNative_getName");
char *name = "yuanjingyao";
return (*env)->NewStringUTF(env, name);
}
JNIEXPORT jint JNICALL
Java_com_yuanxuzhen_yuannative_TestNative_getAge(JNIEnv *env, jclass clazz) {
// TODO: implement getAge()
int a = 10;
return a;
}
JNIEXPORT jobject JNICALL
Java_com_yuanxuzhen_yuannative_TestNative_getAgeInteger(JNIEnv *env, jclass clazz) {
// TODO: implement getAgeInteger()
int a = 30;
jclass NUMBER = (*env)->FindClass(env,"java/lang/Integer");
jmethodID useGenId = (*env)->GetMethodID(env,NUMBER, "<init>",
"(I)V");
jobject useObject = (*env)->NewObject(env,NUMBER, useGenId, a);
return useObject;
}
typedef struct Student{
char *name; //姓名
int num; //学号
int age; //年龄
char group; //所在学习小组
float score; //成绩
} Student;
JNIEXPORT void JNICALL
Java_com_yuanxuzhen_yuannative_TestNative_testNullPoint(JNIEnv *env, jclass clazz) {
// TODO: implement testNullPoint()
LOGE("Java_com_yuanxuzhen_yuannative_TestNative_testNullPoint");
Student* point;
point->name = "abc";
}
//
// Created by yuanxuzhen on 7/16/21.
//
#ifndef JETPACKDEMO_NATIVE_LIB_H
#define JETPACKDEMO_NATIVE_LIB_H
#include <android/log.h>
#include <jni.h>
#include <stdio.h>
#define LOG_TAG "YUANxxx"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,LOG_TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
#define YUAN_TRUE 1
#define YUAN_FALSE 0
#endif //JETPACKDEMO_NATIVE_LIB_H
.c的代码由下面的代码通过android studio自动生成
package com.yuanxuzhen.yuannative;
public class TestNative {
static {
System.loadLibrary("native-lib");
}
public static native String getName();
public static native int getAge();
public static native Integer getAgeInteger();
public static native void testNullPoint();
}
自动生成以前我们必须手动添加一个到native-lib.c中,这样android-studio才知道后续放在那里。
5、配置相应版本的ndk
local.properties
## This file is automatically generated by Android Studio.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file should *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
sdk.dir=/Users/yuanxuzhen/Library/Android/sdk
ndk.dir=/Users/yuanxuzhen/Library/Android/sdk/ndk/21.0.6113669
gradle.properties
android.useDeprecatedNdk=true
这样代码就填好了
接下来 我们添加测试代码
package com.yuanxuzhen.jetpackdemo;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import com.yuanxuzhen.room.StudentData;
import com.yuanxuzhen.room.UserData;
import com.yuanxuzhen.room.YuanDataUtil;
import com.yuanxuzhen.yuannative.TestNative;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MainNativeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("yuanMain", TestNative.getName());
Log.e("yuanMain", TestNative.getAge() + "");
Log.e("yuanMain", TestNative.getAgeInteger() + "");
}
}
运行结果
2021-07-16 17:28:47.656 5978-5978/com.yuanxuzhen.jetpackdemo E/yuanMain: yuanjingyao
2021-07-16 17:28:47.656 5978-5978/com.yuanxuzhen.jetpackdemo E/yuanMain: 10
2021-07-16 17:28:47.672 5978-5978/com.yuanxuzhen.jetpackdemo E/yuanMain: 30