References:The "Android NDK" MacOS Environment uses Gradle to compile JNI modules and configurations in Android Studio: http://demo.netfoucs.com/ashqal/article/details/ 21869151ANDROID STUDIO, GRADLE and NDK Integration:http://ph0b.com/android-studio-gradle-and-ndk-integration/gradle Plugin User guide:http://tools.android.com/tech-docs/new-build-system/user-guidenew Build system:http:// Tools.android.com/tech-docs/new-build-system
practice proves that:0.4.2 only works with Androidlibrary modules created under the gradle1.10 version can be compiled properly, gradle1.9 versions are not available. 0.4.6 can use gradle1.10. The so library can be generated 0.5.0 both gradle1.10 and gradle1.11 versions. 0.5.5 can not compile the NDK, either gradle1.10 or gradle1.11 version can not generate so library, 屙 hematuria and pus.
Download Androidstudio: Androidstudio's historical version download list: Http://tools.android.com/download/studio/canary
Download NDK:Download Link: http://developer.android.com/tools/sdk/ndk/index.html, note the NDK must be r9+ version, otherwise the compile will appear as follows
Error:
Execution failed for task ': Hellojni:compiledebugndk ' .> com.android.ide.common.internal.LoggedErrorException: Failed to Run command: D:\ndk\ndk-build.cmd ndk_project_path=null app_build_script=f:\androidstudio\test\ Hellojni\build\ndk\debug\android.mk app_platform=android-19 Ndk_out=f:\androidstudio\test\hellojni\build\ndk\ Debug\obj ndk_libs_out=f:\androidstudio\test\hellojni\build\ndk\debug\lib app_abi=armeabi,armeabi-v7aerror Code: 2Output: D:/NDK/BUILD/CORE/SETUP-APP.MK:63: * * * Android ndk:aborting . Stop.
Download Gradle:gradle-1.9-all.zip:http://download.csdn.net/detail/xxhongdev/6834859gradle-1.10-all.zip:http:// download.csdn.net/detail/xinghuacheng/7026815gradle-1.11-all.zip:http://download.csdn.net/detail/d1387968/ 7097249
The historical version downloaded through the Androidstudio history download list is usually a green compressed package that can be decompressed directly, but does not include the SDK and requires an additional download of the SDK, since ADT (version: adt20131030) was previously downloaded, So use the SDK in the ADT directory directly behind it. by http://developer.android.com/sdk/installing/ studio.html Home Download Androidstudio for the installation version, including the SDK, can be downloaded directly after installation, the first use of the creation of the project will be slow, you can refer to the "Androidstudio when creating a project is building" project Name "Workaround for Gradle Project Info" to resolve.
To Create a project:After running Androidstudio, create a new project, and the new project will have a default module, where the project name is Jnidemo,module for the app. You then complete the project creation through the wizard. Androidstudio is still very slow, long time in this state: After a long wait to finally complete the project creation, and then under this project to create a module,new module->android Library: Uncheck "Create Activity "then click" Finish "to complete the creation, at this time the project Structure app and Hellojni are the two module under Jnidemo, here Hellojni as the NDK development layer to generate so library, the app as the APK to call so library Reference development layer. Create the JNI directory under the Src/main of the Hellojni module and new file main.cpp under the JNI directory, as follows:
#include <stdio.h> #include <stdlib.h> #include <jni.h> #include <assert.h> #include <sys/ types.h> #include <android/log.h> #define LOG_TAG "Hellojni" #define LOGE (...) __android_log_print (Android_log_error, Log_tag, __va_args__) #define Logi (...) __android_log_print (Android_log_info, Log_tag, __va_args__)//Register Native API class # define JNIREG_CLASS "com/example/test9/ App/mainactivity "extern" C "{jniexport void msg (jnienv *env, Jobject clazz, jstring str);};/ /jstring to char* char* jstringtostring (jnienv* env, jstring jstr) {char* RTN = NULL; Jclass clsstring = Env->findclass ("java/lang/string"); Jstring Strencode = Env->newstringutf ("Utf-8"); Jmethodid mid = Env->getmethodid (clsstring, "GetBytes", "(ljava/lang/string;) [B"); Jbytearray barr= (Jbytearray) Env->callobjectmethod (Jstr, Mid, Strencode); Jsize alen = Env->getarraylength (Barr); jbyte* ba = env->getbytearrayelements (Barr, Jni_false); if (Alen > 0) {RTN = (char*) malloc (alen + 1); memcpy (RTN, BA, Alen); Rtn[alen] = 0; } env->releasebytearrayelements (Barr, BA, 0); return RTN; }jniexport void msg (jnienv *env, Jobject clazz, jstring str) {char *pszstr = NULL; PSZSTR = jstringtostring (env, str); Logi ("%s", PSZSTR); Free (PSZSTR);} /*** Table of methods associated with a single class.*/static jninativemethod gmethods[] = {{"MSG", "(Ljava/lang/stri ng;) V ", (void*) msg},};/** Register native methods for all classes we know about.*/static int Registernativemethods (jnienv* ENV) {int nerror = 0; Jclass clazz = NULL; Clazz = Env->findclass (Jnireg_class); if (clazz = = null) {LOGE ("Clazz is null"); return jni_false; } nerror = Env->registernatives (Clazz, Gmethods, sizeof (gmethods)/sizeof (gmethods[0])); if (Nerror < 0) {LOGE ("Registernatives Error:%d num:%d", nerror, sizeof (gmethods)/sizeof (gmethods[0])); Return JNI_FALSE; } return jni_true;} /** Set Some test stuff up.** Returns the JNI version on Success,-1 on Failure.*/jniexport jint jnicall jni_onload (JAVAVM * VM, void* reserved) {jnienv* env = NULL; Jint result =-1; if (vm->getenv (void**) &env,jni_version_1_6)! = JNI_OK) {return-1; } assert (env! = NULL); if (!registernativemethods (env)) {LOGE ("Registernativemethods failed"); return-1; }/* Success--Return valid version number */result = Jni_version_1_6; return result;}
Only one MSG function is exported here to print the passed in string, only for testing. Then create a new Empty.cpp file in the Jni directory, empty, this is to solve the NDK bug, in case of compilation error. Open Local.properties, set the correct SDK path and NDK path:
Sdk.dir=d\:/adt20131030/sdkndk.dir=d\:/ndk
Open the Project Gradle/wrapper directory under the Gradle-wrapper.properties file, modify:
#Wed APR 15:27:10 PDT 2013distributionbase=gradle_user_homedistributionpath=wrapper/distszipstorebase=gradle_ User_homezipstorepath=wrapper/distsdistributionurl=http\://services.gradle.org/distributions/gradle-1.9-all.zip
For:
#Wed APR 15:27:10 PDT 2013distributionbase=gradle_user_homedistributionpath=wrapper/distszipstorebase=gradle_ User_homezipstorepath=wrapper/distsdistributionurl=http\://services.gradle.org/distributions/gradle-1.10-all.zip
and open the project root directory under the Build.gradle file, modify:
Top-level build file where can add configuration options common to all Sub-projects/modules.buildscript { repos itories { mavencentral () } dependencies { classpath ' com.android.tools.build:gradle:0.7.+ ' }} allprojects { repositories { mavencentral () }}
For (Specify use gradle1.10 to modify to 0.9.+, specify use gradle1.11 to modify to 0.9.2):
Top-level build file where can add configuration options common to all Sub-projects/modules.buildscript { repos itories { mavencentral () } dependencies { classpath ' com.android.tools.build:gradle:0.9.+ ' }} allprojects { repositories { mavencentral () }}
Explanation: Reference Http://tools.android.com/tech-docs/new-build-system know
0.7.0Requires Gradle 1.9Requires Studio 0.4.0
0.9.0Compatible with Gradle 1.10 and 1.11Using Gradle 1.11 requires Android Studio 0.5.0
If you configure 0.7.+, gradle1.9 is used by default, and gradle1.10 is used by default if set to 0.9.+. Also note that there is no buildtypes tag under gradle1.9, you need to put the debug, release tag directly in the Android tag, under gradle1.10 Debug, Release needs to be placed in the buildtypes tag, buildtypes in Android. Here Hellojni configuration of the Build.gradle file content is as follows:
Assert gradle.gradleversion >= "1.10" Apply plugin: ' Android-library ' Android {compilesdkversion buildtoolsvers Ion "19.0.3" Defaultconfig {minsdkversion 8 targetsdkversion versioncode 1 versionname "1.0"} buildtypes {release {Runproguard false proguardfiles getdefaultproguardfile (' Proguard-android.txt '), ' Proguard-rules.txt ' ndk {modulename "Hellojni" Abifilte Rs "Armeabi", "armeabi-v7a", "x86"}} debug {ndk {modulename "Helloj Ni "//stl" stlport_shared "ldlibs" log "," Z "," M "//cflags"-wall-wextra-i "+ ProjectDir +"/src/main/jni/include "Abifilters" Armeabi "," armeabi-v7a "," x86 "}} } productflavors {x86 {Versioncode integer.parseint ("6" + Defaultconfig.versioncode) n DK {abifIlter "x86"}} MIPS {Versioncode integer.parseint ("4" + Defaultconfig.versioncode) NDK {Abifilter "MIPS"}} armv7 {Versioncode Integer.parsei NT ("2" + Defaultconfig.versioncode) ndk {abifilter "armeabi-v7a"}} A RM {Versioncode Integer.parseint ("1" + Defaultconfig.versioncode) ndk {abifilters " Armeabi "," armeabi-v7a "}} fat}}dependencies {compile ' com.android.support:appcompat-v7: 19.+ ' Compile Filetree (dir: ' Libs ', include: [' *.jar '])}
Then select Hellojni Project Right "make Module hellojni", wait for a period of time will be generated under the project BUILD-NDK directory, there will be some different versions of so library files generated, Note that the Android.mk file here is automatically generated by the tool each time it is compiled, rather than manually edited, which I think is a poor design. For example, if you want to use the log output function __android_log_print, you need to add "local_ldlibs: =-llog", then add the following configuration in the Build.gradle file:
Debug { ndk { ldlibs ' log ' } }
The Gradle is configured to generate the Android.mk file, and then the NDK is called to compile. Right-click Project Select Open Module Settings, select Modules-app, open the Dependencies tab, click the "+" sign, select Module dependency, select Hellojni in the dialog box that opens. However, the test finds that the settings depend on no effect, and if you compile app,hellojni directly and do not compile, you still need to compile hellojni manually.
call the native function:In the app project, declare the native function in the Mainactivity class:
public native void msg (String str);
and add static code to load the HELLOJNI library:
static { system.loadlibrary ("Hellojni"); }
In Mainactivity::oncreate, call the native function to print a sentence of log:
@Override protected void onCreate (Bundle savedinstancestate) { super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); msg ("Mainactivity onCreate"); }
You also need to package the HELLOJNI generated so library file into the APK, still need to configure the Build.gradle file, add:
Task Copynativelibs (type:copy) {from filetree (dir: '). /hellojni/build/ndk/arm/debug/lib ', include: ' armeabi/*.so ') into ' build/lib '}tasks.withtype (Compile) { Compiletask-Compiletask.dependson Copynativelibs}clean.dependson ' cleancopynativelibs ' Tasks.withType ( com.android.build.gradle.tasks.PackageApplication) {Pkgtask , pkgtask.jnifolders = [New File (BuildDir, ' Lib ' )]}
Reference: "Android studio Add so Library" http://blog.csdn.net/caesardadi/article/details/18264399 where Copynativelibs task is from relative app's project path ' .. /hellojni/build/ndk/arm/debug/lib ' Copy all the Armeabi subdirectory's so files into the Lib directory under this project build directory, Execution effect: So the last package generated APK package will contain the so library file with Hellojni.
Test:
Compile run app,apk The run-time output log information: The possible Gradle errors and solutions are listed later for reference.
Error:
Execution failed for task ': Hellojni:compiledebugndk ' .> com.android.ide.common.internal.LoggedErrorException: Failed to Run command: D:\ndk\ndk-build.cmd ndk_project_path=null app_build_script=f:\androidstudio\test\ Hellojni\build\ndk\debug\android.mk app_platform=android-19 Ndk_out=f:\androidstudio\test\hellojni\build\ndk\ Debug\obj ndk_libs_out=f:\androidstudio\test\hellojni\build\ndk\debug\lib app_abi=armeabi,armeabi-v7aerror Code: 2Output: make.exe: * * * No rule to make target ' f:\androidstudio\test\hellojni\build\ndk\debug\obj/local/ Armeabi/objs/jnimain/f_\androidstudio\test\hellojni\src\main\jni ', needed by ' F:\androidstudio\test\hellojni\ BUILD\NDK\DEBUG\OBJ/LOCAL/ARMEABI/OBJS/JNIMAIN/F_\ANDROIDSTUDIO\TEST\HELLOJNI\SRC\MAIN\JNI\HELLOJNI.O '. Stop.
Solution:This is the NDK next bug in Windows, when only one file is compiled, the workaround is to add an empty file. See http://ph0b.com/android-studio-gradle-and-ndk-integration/in the original:
This could come from a current NDK bug on Windows, when there was only one source file to compile. You have need to add one empty source to make it work again.
Error:
Could not determine the dependencies of tasks ': Hellojni:compilearmdebugjava ' .> failed to find Build Tools revision 19.0 .3
Solution:This build tools refers to "Android SDK Build-tools" and opens the SDK Manager to check the appropriate version (for example, 19.0.3) to install.
Error:
Failure:build failed with a exception.* what went wrong:task ' assemblearmdebug ' isn't found in project ': Hellojni '. Some candidates is: ' Assembledebug '. * Try:run gradle tasks to get a list of available tasks. Run with--STACKTRACE option to get the stack trace. Run with--info or--debug option to get more log output.
Solution Solutions: In
Android {}Added in:
productflavors{ arm { } }
If you have a similar error, refer to the appropriate tag:
productflavors { x86 { Versioncode integer.parseint ("6" + Defaultconfig.versioncode) ndk { abifilter "x86" } } MIPS { versioncode integer.parseint ("4" + Defaultconfig.versioncode) NDK { Abifilter "MIPS" } } armv7 { versioncode integer.parseint ("2" + Defaultconfig.versioncode) NDK { abifilter "armeabi-v7a" } } arm { versioncode integer.parseint ("1" + Defaultconfig.versioncode) ndk { abifilter "Armeabi" //abifilters "Armeabi", "armeabi-v7a" } } Fat }
Error:
Execution failed for task ': Hellojni:compiledebugndk ' .> java.io.IOException:Cannot Run Program ' D:\ndk\ndk-build ': CreateProcess error=193,%1?????? Mainland?? Win32?? Ó
Solution:Encountered while using the gradle1.9 version, use the gradle1.10 version to resolve.
Error:
A problem occurred evaluating project ': App ' .> Could not create plugin of type ' Appplugin '.
Solution:Don ' t use latest Gradle (version 1.10), downgrade to 1.9. Reference: http://blog.vyvazil.eu/tag/android-studio/But if we use the gradle1.9 version then it will appear
Error:
Execution failed for task ': Hellojni:compiledebugndk ' .> java.io.IOException:Cannot Run Program ' D:\ndk\ndk-build ': CreateProcess error=193,%1?????? Mainland?? Win32?? Ó
Regardless of which version of the problem, and then carefully review the next ' Appplugin ' This error is appearing on the ' app ' module rather than ' Hellojni ' module, so consider a new project and only in the project to build a library module, no longer create the app module, here does not tick " Create custom Launcher Icon "and" Create activity ", direct finish finish, other configuration reference described above, after the final compilation can generate so library files:
Error:This mistake forgot to record the embarrassment
Solution:File-settings-gradle-gradle VM options:-xmx512m
Using Androidstudio to compile NDK methods and error Solutions