使用Gradle编译C/C++源码步骤
申明NDK工具类,内部定义native方法
package com.coca.firstdemo; /** * Created by Administrator on 2016/6/6. */public class JniShareUtils { public native String getLogCount(String params);}
定位至项目的app文件夹,调用javah命令生成.h文件:
javah com.coca.firstdemo.JniShareUtils
执行完会在.java文件同目录下生成com_coca_firstdemo_JniShareUtils.h文件,内容如下:
/* DO NOT EDIT THIS FILE - it is machine generated */#include <jni.h>/* Header for class com_coca_firstdemo_JniShareUtils */ #ifndef _Included_com_coca_firstdemo_JniShareUtils#define _Included_com_coca_firstdemo_JniShareUtils#ifdef __cplusplusextern "C" {#endif/* * Class: com_coca_firstdemo_JniShareUtils * Method: getLogCount * Signature: (Ljava/lang/String;)Ljava/lang/String; */JNIEXPORT jstring JNICALL Java_com_coca_firstdemo_JniShareUtils_getLogCount (JNIEnv *, jobject, jstring); #ifdef __cplusplus}#endif#endif
在app文件夹下新建jni目录存放生成的.h文件。新建.c文件,名字随意,内容如下:
#include "com_coca_firstdemo_JniShareUtils.h" JNIEXPORT jstring JNICALL Java_com_coca_firstdemo_JniShareUtils_getLogCount (JNIEnv *env, jobject obj, jstring jstr){ return (*env)->NewStringUTF(env,"This just a test for Android Studio NDK JNI developer!");}
在app的build.gradle中添加设置(ABI支持的7种平台: armeabi, armeabi-v7a, x86, x86_64, mips, mips64, arm64-v8a
defaultConfig { //... ndk{ moduleName "wangjun_so_jni" //生成的so名字,名字随意 abiFilters "armeabi", "armeabi-v7a", "x86" //输出指定三种abi体系结构下的so库。目前可有可无。 }}
在JniShareUtils中添加静态初始化代码:
static { System.loadLibrary("wangjun_so_jni");//与上述build.gradle中定义的moduleName对应}
为什么不用建立Android.mk文件?
在app的build.gradle中按住ctrl点击ndk代码块的modelName即可跳转至NdkOptions.java文件
package com.android.build.gradle.internal.dsl;/** * DSL object for NDK-related settings. */public class NdkOptions implements CoreNdkOptions, Serializable { private static final long serialVersionUID = 1L; private String moduleName; private String cFlags; private List<String> ldLibs; private Set<String> abiFilters; private String stl; private Integer jobs;}
即ndk代码块中可设置的参数有5个,代替了Android.mk中的参数设置。
小Tips:
1.提示错误:Error: NDK integration is deprecated in the current plugin. Consider trying the new experimental plugin. For details, see http://tools.android.com/tech-docs/new-build-system/gradle-experimental. Set "android.useDeprecatedNdk=true" in gradle.properties to continue using the current NDK integration.
解决:在gradle.properties中添加android.useDeprecatedNdk=true
时间: 2024-10-28 13:13:50