AndroidStudio2.0 Build NDK Environment & successfully compile and use

Source: Internet
Author: User

Now the use of the NDK to develop a lot of scenes, game engine, audio and video development can be involved, the previous project is mostly Eclipse's engineering catalog, but the app development is now mostly in the Androidstudio development tools, then there is a problem? How to build the NDK environment in as. This is the answer to this article, and a small example is created, compiled into a. So file, and used in the project. Come on ....

Before we do anything, let's think about how we do it. If we create a new As2.0 project, and then according to his directory structure to put the JNI layer files in the specified directory, and then develop, although feasible, feasible, but the cost is the SDK development and NDK development is separated, not in a project directory, does not meet our expectations, then a different way of thinking about it. Fortunately, as the Gradle script function is more powerful, you can specify the source files, operation tasks and so on. If you just modify the configuration file, it is good to do things, it would not be happy. All right, let's do it.

First create a JNI directory under the SRC directory of the Engineering module (store our C, C + + source and Mk files)

Then the most important thing is to configure the Build.gradle in the JNI code is our NDK compiled code location, and do some processing of the compiler task below configuration code provided by the Chengdu Small Demon , especially thank him

Task Buildnative (type:exec, Description:' Compile JNI source via NDK ') {def ndkdir = Android.ndkdirectoryif(Os.isfamily (Os.family_windows)) {CommandLine "$ndkDir/ndk-build.cmd",'-C ',file(' Src/jni '). Absolutepath,//Change Src/main/jni the relative path to your JNI source                '-j ', Runtime.runtime.availableProcessors (),' All ',' ndk_debug=1 '}Else{CommandLine "$ndkDir/ndk-build",'-C ',file(' Src/jni '). Absolutepath,//Change Src/main/jni the relative path to your JNI source                '-j ', Runtime.runtime.availableProcessors (),' All ',' ndk_debug=1 '}}//CommandLine "$ndkDir/ndk-build" in Mac, but CommandLine "$ndkDir/ndk-build.cmd" in Windows, amount, Pit//Task Cleannative (type:exec, Description:' Clean JNI object files ') {def ndkdir = Android.ndkdirectoryif(Os.isfamily (Os.family_windows)) {CommandLine "$ndkDir/ndk-build.cmd",'-C ',file(' Src/jni '). Absolutepath,//Change Src/main/jni the relative path to your JNI source                ' Clean '}Else{CommandLine "$ndkDir/ndk-build.cmd",'-C ',file(' Src/jni '). Absolutepath,//Change Src/main/jni the relative path to your JNI source                ' Clean '}}//Clean.dependson' cleannative 'Tasks.withtype (javacompile) {compiletask-Compiletask.dependson buildnative}

Note that there is a change in the above where the JNI path is,src/jni , if it's not the same as mine, you should write your exact location.

Then add a native method to our code and let him print a HelloWorld.

public native void printHelloworld();

Then use the javah command to generate the corresponding. h header file

This will generate 2 files in the following directory, of course, the following file does not care about it

and put the resulting files in the jni you just created.
Here's how to write cpp files and android.mk application.mk files.

. h File Codes

/* Don't EDIT this file-it are machine generated * /#include <jni.h>/ * Header for class com_qbao_ticket_mainactivity * /#ifndef _included_com_qbao_ticket_mainactivity#define _included_com_qbao_ticket_mainactivity#ifdef __cplusplusextern"C"{#endif/* * class:com_qbao_ticket_mainactivity * Method:add * Signature: () V */JniexportvoidJnicallJava_com_qbao_ticket_mainactivity_printhelloworld (jnienv *, jobject);#ifdef __cplusplus}#endif#endif

. cpp file Codes

#include <jni.h>#include <android/log.h>#include "com_qbao_ticket_MainActivity.h"#define LOG_TAG "System.out.c"#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)void JNICALL Java_com_qbao_ticket_MainActivity_printHelloworld  (JNIEnv *, jobject){  LOGI("hello world! come from jni");}

Note that when you create a new write, you must add

#include "com_qbao_ticket_MainActivity.h"

Then write our Mk file, first come to ANDROID.MK

LOCAL_PATH:$(call my-dir)include$(CLEAR_VARS)LOCAL_MODULE    := lalalaLOCAL_SRC_FILES:= com_qbao_ticket_MainActivity.cppLOCAL_LDLIBS += -lloginclude$(BUILD_SHARED_LIBRARY)

The place to change is our module name and the list of source files here, according to your own code settings.

Next Application.mk

APP_ABI := allAPP_PLATFORM := android-8

Set up the whole platform, of course not set can also default on the line

Click this button to start compiling

Successful compilation generates a Libs and obj.local directory in the SRC directory
And then we created the liblalala.so file format we named as the lib{module name}.so

Here's how to use the. So file that we generated in the code.

Copy our compiled build good. So file to the code in the Libs Armeabi directory

And then it's used in our code.

static {   System.loadLibrary("lalala");}publicnative  voidprintHelloworld();

Note that when load is written, the module name is not the file name here is Lalala and then in Mainactivity call this Printhelloworld method
Print the log, please.

Okay, here we go. Building the NDK environment in As2.0 and compiling the so file, and using the so file is finished, the following will be compiled on this basis some audio and video module code, and then encapsulated use. Look forward to it ...

Build.gradle All Configuration View

Import org.apache.tools.ant.taskdefs.condition.Osapply Plugin:' Com.android.application 'dependencies {Compile Filetree (dir:' Libs ', include:' *.jar ')}android {compilesdkversion +Buildtoolsversion"22.0.1"Sourcesets {main {manifest.srcfile' Androidmanifest.xml 'Java.srcdirs = [' src '] Resources.srcdirs = [' src '] Aidl.srcdirs = [' src '] Renderscript.srcdirs = [' src '] Res.srcdirs = [' Res '] Assets.srcdirs = [' Assets '] Jnilibs.srcdirs = [' Libs ']}//Move The tests to Tests/java, tests/res, etc ... Instrumenttest.setroot (' tests ')//Move The build types to build-types/<type>//For instance, Build-types/debug/java, build-types/d Ebug/androidmanifest.xml,...This moves them out of them default location under src/<type>/...which would//conflict with src/being used by the mainSourceSet.        Adding New build types or product flavors should be accompanied//by a similar customization. Debug.setroot (' Build-types/debug ') Release.setroot (' Build-types/release ')} buildtypes {debug {//proguardfile'/users/xuchuang/desktop/stifler/workspace/qbaoticket_2.0/qbaoticket_2.0/proguard-project.txt 'Signingconfig Signingconfigs.qbaoticket} release {//signingconfig signingconfigs.qbaoticket minifyenabled true//proguardfile'/users/xuchuang/desktop/stifler/workspace/qbaoticket_2.0/qbaoticket_2.0/proguard-project.txt '}} compileoptions {sourcecompatibility javaversion.version_1_7 targetcompatibility JavaVersion.VERSI On_1_7} dexoptions {Jumbomode true}}task buildnative (type:exec, Description:' Compile JNI source via NDK ') {def ndkdir = Android.ndkdirectoryif(Os.isfamily (Os.family_windows)) {CommandLine"$ndkDir/ndk-build.cmd",'-C ', File (' Src/jni '). Absolutepath,//change Src/main/jni the relative path to your JNISource                '-j ', Runtime.runtime.availableProcessors (),' All ',' ndk_debug=1 '}Else{CommandLine"$ndkDir/ndk-build",'-C ', File (' Src/jni '). Absolutepath,//change Src/main/jni the relative path to your JNISource                '-j ', Runtime.runtime.availableProcessors (),' All ',' ndk_debug=1 '}}//CommandLine in Mac"$ndkDir/ndk-build", but in Windows CommandLine"$ndkDir/ndk-build.cmd", amount, Pit//task cleannative (type:exec, Description:' Clean JNI object files ') {def ndkdir = Android.ndkdirectoryif(Os.isfamily (Os.family_windows)) {CommandLine"$ndkDir/ndk-build.cmd",'-C ', File (' Src/jni '). Absolutepath,//change Src/main/jni the relative path to your JNISource                ' Clean '}Else{CommandLine"$ndkDir/ndk-build.cmd",'-C ', File (' Src/jni '). Absolutepath,//change Src/main/jni the relative path to your JNISource                ' Clean '}}//clean.dependson' cleannative 'Tasks.withtype (javacompile) {compiletask-Compiletask.dependson buildnative}

Resources
http://blog.csdn.net/allen315410/article/details/41805719

Support original from the outbreak of the girl QQ 928320442

AndroidStudio2.0 Build NDK Environment & successfully compile and use

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.