本文AndroidStudio版本 3.2.1
JNI开发流程
1. 编写java部分
Java中声明native方法
/home/nan/Work/jniProject/com/nan/JniTest.java
package com.nan;
import java.lang.System;
public class JniTest {
// 1. 加载动态库
static {
System.loadLibrary("jni-test");
}
public static void main(String[] args) {
JniTest jniTest = new JniTest();
System.out.println(jniTest.get());
jniTest.set("hello world");
}
public native String get();
public native void set(String str);
}
2. 编写jni部分
1. 编译java源文件得到class文件,通过javah命令到处jni的头文件
命令如下
nan@breeze:~/Work/jniProject$ javac com/nan/JniTest.java
nan@breeze:~/Work/jniProject$ javah com.nan.JniTest
当前目录下会生成一个com_nan_JniTest.h头文件,用于编写对应jni cpp用
/home/nan/Work/jniProject/com_nan_JniTest.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_nan_JniTest */
#ifndef _Included_com_nan_JniTest
#define _Included_com_nan_JniTest
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_nan_JniTest
* Method: get
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_nan_JniTest_get
(JNIEnv *, jobject);
/*
* Class: com_nan_JniTest
* Method: set
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_com_nan_JniTest_set
(JNIEnv *, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif
2. 实现jni方法
将com_nan_JniTest.h复制到jni目录下,接着创建test.cpp文件
/home/nan/Work/jniProject/jni/test.cpp
#include "com_nan_JniTest.h"
#include <stdio.h>
JNIEXPORT jstring JNICALL Java_com_nan_JniTest_get
(JNIEnv *env, jobject thiz) {
printf("invoke get() in c++\n");
return env->NewStringUTF("Hello from JNI!");
}
JNIEXPORT void JNICALL Java_com_nan_JniTest_set
(JNIEnv *env, jobject thiz, jstring string) {
printf("invoke set() in c++\n");
char* str = (char*)env->GetStringUTFChars(string,NULL);
printf("%s\n",str);
env->ReleaseStringUTFChars(string, str);
}
3. 编译so库
编译命令如下
nan@breeze:~/Work/jniProject/jni$ gcc -shared -I /usr/lib/jvm/java-7-openjdk-amd64/include -fPIC test.cpp -o libjni-test.so
jni目录下会生成libjni-test.so库文件.
注:
Ubuntu16.04,gcc为4.8时报如下错误.
gcc: error trying to exec 'cc1plus': execvp: No such file or directory
gcc切换为5.4.0时执行成功.
4. 执行java程序并调用native方法
nan@breeze:~/Work/jniProject$ java -Djava.library.path=jni com.nan.JniTest
invoke get() in c++
Hello from JNI!
invoke set() in c++
hello world
NDK开发流程
1. 手动ndk-build
1. 新建Android Project,并使用AndroidStudio下载ndk-bundle
新建Project->F4->SDK Location->Android NDK location->点击Download->完成后如图
2. 声明所需的native方法
通过MainActivity中的按钮点击后从native层获取字符串设置给TextView,并给native层设置字符串
public class MainActivity extends Activity {
public static final String TAG = "breeze";
static {
System.loadLibrary("jni-test");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tvContent = findViewById(R.id.tv_content);
Button btnCaller = findViewById(R.id.btn_call);
btnCaller.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvContent.setText(get());
set("I am from JniProject app!");
}
});
}
public native String get();
public native void set(String str);
}
3. 编写native方法
在main目录下创建jni目录,创建test.cpp
/home/nan/AndroidStudioProjects/JniProject/app/src/main/jni/test.cpp
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
#include <stdio.h>
/* Header for class com_nan_jniproject_MainActivity */
#ifndef _Included_com_nan_jniproject_MainActivity
#define _Included_com_nan_jniproject_MainActivity
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_nan_jniproject_MainActivity
* Method: get
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_nan_jniproject_MainActivity_get
(JNIEnv * env, jobject thiz) {
printf("invoke get in c++\n");
return env->NewStringUTF("I am from Jni in libjni-test.so !");
}
/*
* Class: com_nan_jniproject_MainActivity
* Method: set
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_com_nan_jniproject_MainActivity_set
(JNIEnv * env, jobject thiz, jstring string){
printf("invoke set in c++\n");
char* str = (char*)env->GetStringUTFChars(string,NULL);
printf("%s\n",str);
env->ReleaseStringUTFChars(string,str);
}
#ifdef __cplusplus
}
#endif
#endif
没有独立的头文件,声明和实现均在test.cpp中. 但我们编写时可通过javah com.nan.jniproject.MainActivity
先生成头文件,然后将其内容拷贝至test.cpp中,然后改下方法体即可.
4. 创建Android.mk编译规则为cpp文件
/home/nan/AndroidStudioProjects/JniProject/app/src/main/jni/Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
# 模块名称
LOCAL_MODULE := jni-test
# 源代码文件
LOCAL_SRC_FILES := test.cpp
include $(BUILD_SHARED_LIBRARY)
5. 创建Application.mk来指定so库生成的目标CPU架构类型
armeabi-v7a最常用,故指定该类型
/home/nan/AndroidStudioProjects/JniProject/app/src/main/jni/Application.mk
APP_ABI := armeabi-v7a
6. 编译so库并运行Project
- ndk-build命令编译so库
nan@breeze:~/AndroidStudioProjects/JniProject/app/src/main$ ndk-build
Android NDK: APP_PLATFORM not set. Defaulting to minimum supported version android-16.
Android NDK: WARNING: APP_PLATFORM android-16 is higher than android:minSdkVersion 1 in ./AndroidManifest.xml. NDK binaries will *not* be compatible with devices older than android-16. See https://android.googlesource.com/platform/ndk/+/master/docs/user/common_problems.md for more information.
[armeabi-v7a] Compile++ thumb: jni-test <= test.cpp
[armeabi-v7a] StaticLibrary : libstdc++.a
[armeabi-v7a] SharedLibrary : libjni-test.so
[armeabi-v7a] Install : libjni-test.so => libs/armeabi-v7a/libjni-test.so
可以看到libjni-test.so已生成在libs目录下/home/nan/AndroidStudioProjects/JniProject/app/src/main/libs/armeabi-v7a/libjni-test.so
- AndroidStudio默认识别的so库文件夹main/jniLibs/,故我们在main下创建jniLibs目录,将刚才libs下生成的直接拷到该位置
/home/nan/AndroidStudioProjects/JniProject/app/src/main/jniLibs/armeabi-v7a/libjni-test.so
- 除此外还需在Module的build.gradle配置参数如图
注意build.gradle中添加了sourceSets部分,关注注释1和2部分 - 运行代码
这时代码可以正常运行,点击Button后会调用native函数并在TextView上显示"I am from Jni in libjni-test.so !"
2. AndroidStudio自动ndk-build
手动写cpp没有任何提示功能,且编译移动文件繁琐,通过AndroidStudio配置可实现一键编译运行,代码回到初识创建状态,一步一步来.
1. 声明所需native方法(同上)
2. 创建jni Folder
创建后就会在Project视图下多出cpp文件夹,这个里面就是用来写c++的
3. 编写Android.mk
在cpp文件夹下编写Android.mk,可以将上面的Android.mk直接考入即可.先将源文件注释掉,因为还没有c++文件,待编写后加入即可
4. 编写c++文件
首先配置自动编译且可以编写c++有提示功能
File->Link C++ Project with Gradle->Build System选项选择ndk-build方式->Project path选择Android.mk文件->OK 这时Studio就会自动编译
这时可以cpp下创建c++文件进行编写,已经有提示功能了哦,也可以直接将上面的test.cpp直接拷入,然后在Android.mk源文件进行指定. 这时已可以运行代码了
5. 运行程序
运行后产生的so库文件和第4步配置后的build.gradle的变化一并展示,如图
可以发现AndroidStudio默认会生成如图4个cpu架构的so库. 对于build.gradle只多出了注释1的部分.
6. AndroidStudio指定so库CPU架构
build.gradle中配置
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.nan.jniproject"
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
// 1. 添加该部分 {
ndk {
abiFilters 'armeabi-v7a' // , ‘arm64-v8a’, ‘x86’, ‘x86_64’
}
// }
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
externalNativeBuild {
ndkBuild {
path file('src/main/jni/Android.mk')
}
}
}
注释1部分就加入了指定cpu类型,指定armeabi-v7a,如果要支持其他加入即可,armeabi-v7a基本上涵盖了市面上绝大部分手机.
注意ndk{}必须放在defaultConfig下,否则报如下错.
Could not find method ndk() for arguments
至此开发流程我们就清楚了!!!