Android之JNI:Android Studio使用Gradle編譯C/C++源碼

使用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 __cplusplus
extern "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


相關文章
相關標籤/搜索