项目需要使用jni开发,之前电脑没有安装过相关工具,现在咱们从头开始。
1,安装NDK和CMake,在Android Studio界面Ctrl+Alt+S进到settings界面,选中CMake和NDK,点击Apply,会自动安装
2,在项目中新建myJNI.java文件,和MainActivity同级目录就行,如图
3,编辑myJNI.java文件,代码如下:
package com.example.myapplication;
public class myJNI {
static {
System.loadLibrary("JniTest");
}
public static native String sayHello();
}
4,点击Android Studio的Terminal,进入终端,执行命令javac myJNI.java,会在目录里生成一个myJNI.class
5,然后执行javac -h myJNI.java,会生成一个头文件
6,新建一个文件夹jni,并且新建一个c文件main.c
7,将刚刚生成的com_example_myapplication_myJNI.h文件中方法实现后,拷贝到main.c中,代码如下:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_example_myapplication_myJNI */
#ifndef _Included_com_example_myapplication_myJNI
#define _Included_com_example_myapplication_myJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_example_myapplication_myJNI
* Method: sayHello
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_example_myapplication_myJNI_sayHello
(JNIEnv *env, jclass jobject){
return (*env)->NewStringUTF(env,"Hello Maybe");
}
#ifdef __cplusplus
}
#endif
#endif
8,在app路径下新建文件CMakeLists.txt,并配置该文件,
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. 设置生成so文件名
JniTest
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s). 要编译的C/C++文件
src/main/jni/main.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. 指定连接的目标库
JniTest
# Links the target library to the log library
# included in the NDK.
${log-lib} )
9,配置app的build.gradle,在defaultConfig内添加如下代码:
在defaultConfig外,android内添加如下代码:
10,Rebuild Project,重新构建项目
11,在app/build/intermediates/cmake/debug/obj/armeabi-v7a路径下找到so文件
12,在main路径下新建文件夹jniLibs,拷贝一份刚生成的so文件到这个路径下
13,可以在代码中通过jni调用方法了
完工了~~~