Android Dev Intro - Android NDK with Android Studio

转载 2016年05月31日 15:24:04


https://shaneenishry.com/blog/2014/08/17/ndk-with-android-studio/


Unless you are using a game engine with an integrated scripting language, game development is usually done with C++. On the other hand, most Android applications are developed with Java.

This post will explain how to integrate C++ code into Android Studio, use gradle to build it and clear out some misconceptions.

If you used Eclipse you probably know there was a relatively easy way to add "native library" support to your project but now that most projects are being moved to the newer Android Studio it seems like there is no more C++ support. That is incorrect.

There are two ways to add C++ code code into your project. The first is by including prebuilt libraries which you have compiled elsehwere or were pre-compiled for you. The other is to compile them directly from your Android Studio project.

Including pre-built C++ libraries

Including pre-built libraries is simple. Android Studio will look for a specific directory tree and copy all libraries it finds.

The folder structure should be in your Android Studio module's folder and look like this

  • [module_name]
  • * [src]
  • * * [main]
  • * * * [jniLibs]
  • * * * * [armeabi]
  • * * * * [armeabi-v7a]
  • * * * * [x86]
  • * * * * [mips]

Make sure the folder tree is located inside your module, not inside your project root. For example **[projectroot]/app/...**_

The names of the end folders are the same as the ABI the library was compiled for. Make sure to add new ones when you compile for arm64-v8ax86-64 and mips64.

This is how it looks like from Android Studio:

Now you can load your shared libraries (.so) from Android using

String libName = "helloNDK"; // the module name of the library, without .so
System.loadLibrary( libName );

Note that compiling a shared library with the ndk generatres a lib + yourModuleName + .so. When loading your library you should only call your module's name, without the prefix and suffix.

Changing the jniLibs folder

If for some reason you want your C++ libraries path to be somewhere else, you can change it by settingsourceSets.main.jniLibs.srcDirs in your module's build.gradle:

android {

    // .. android settings ..

    sourceSets.main {
        jniLibs.srcDir 'src/main/myCppLibraries' // <-- Set your folder here!
    }
}

Compiling C++ in Android Studio

Adding precompiled libraries is easy but tabbing between terminal and Android Studio can be annoying. If you are developing your C++ code with Android Studio and want it to be compiled when you build your .apk this is how you can do it.

There are 3 things you need to do:

  1. Add ndk.dir variable inside the local.properties file.
  2. Configure ndk module with gradle.
  3. Add C++ files to the expected folder.
  4. (Optional) Set product flavors.

Adding ndk.dir variable

The first thing to do is to configure the path to your ndk folder. Inside your proejct's root folder there should be a file called local.properties. Add a ndk.dir variable directing to your ndk folder. For example:

sdk.dir=/Users/shanee/Development/Android/sdk
ndk.dir=/Users/shanee/Development/ndk

That was easy!

Configuring ndk with gradle

Ok, now to tell gradle to compile our C++ code.

Inside your module's build.gradle file locate your android's defaultConfig section and add the following:

ndk {
    moduleName "moduleNameHere"
}

Make sure to replace the string with your module's name!

Here is mine for reference:

android {
    compileSdkVersion 19
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "com.example.ndksample"
        minSdkVersion 9
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"

        ndk {
            moduleName "myEpicGameCode" // <-- This is the name of my C++ module!
        }
    }

    // ... more gradle stuff here ...

} // end of android section

Note that you can also add additional C++ configuration such as cFlagsstl and ldLibs.

ndk {
    moduleName "myEpicGameCode"
    cFlags "-DANDROID_NDK -D_DEBUG DNULL=0" // Define some macros
    ldLibs "EGL", "GLESv3", "dl", "log"         // Link with these libraries!
    stl "stlport_shared"                        // Use shared stlport library
}

Adding C++ source files

Now that Android Studio and Gradle are configured to compile C++ source code it is time to feed them some files!

Naturally, Gradle expects the C++ files to be inside [module]/src/main/jni/. Simply adding your files there will do the trick:

The next time you try to run the application, gradle will build the C++ module for you. It will even shout at you for C++ errors in the gradle console, for example I added this bad_function:

void bad_function()
{
    int myInt = 4;
    myInt = 10
}

And gradle responded with:

Changing the folder of your source files

Just like with the jniLibs folder, you can tell gradle to look for your C++ files in a different path. I for example prefer my source code inside source. I can set it by editing the sourceSets.main.jni.srcDirs variable:

android {

    // .. android settings ..

    sourceSets.main {
        jni.srcDirs 'src/main/source'
    }
}

(Optional) Setting product flavors

You can set different compilation variables for different platforms. For example you might want to define a different macro for x86 and arm to use different optimizations or to include different header files.

You can do this by adding the productFlavors section under android in the module's build.gradle file.

The most obvious setting would be to avoid compiling the library for all platforms when building the .apk for a specific ABI. For that you can use the abiFilter variable:

android {

    // .. android settings ..

    productFlavors {
        x86 {
            ndk {
                abiFilter "x86"
            }
        }
        arm {
            ndk {
                abiFilter "armeabi-v7a"
            }
        }
        mips {
            ndk {
                abiFilter "mips"
            }
        }
    }

} // android

The next time you build your project for a specific ABI target the ndk will know which build type it should create and not to use the default abi settings which is to compile for all platforms.

You can also override the default cFlags and other settings here, just add them inside the ndk section under the build of your choice.

Summary

I oriented this guide toward people who are looking to convert their project from Eclipse to Android Studio and omitted explanation on how to use JNI and call C++ functions from Java/Android. If there is demand for a JNI tutorial I will write a post for it.

Hope this post was helpful for you! Keep making awesome games for Android :)


Android Dev Intro - Android NDK with Android Studio

Android NDK C++ 开发利器:Android Studio 在今年的Google IO大会上,Google宣布Android Studio开始支持NDK开发。通过和JetBrains...
  • fanbird2008
  • fanbird2008
  • 2016年05月31日 10:02
  • 225

AndroidStudio如何配置NDK/JNI开发环境

参考文章: http://www.th7.cn/Program/Android/201509/550864.shtml http://www.open-open.com/lib/view/open14...
  • aplixy
  • aplixy
  • 2016年05月16日 22:41
  • 44450

[Android] 环境配置之Android Studio开发NDK

NDK 开发哪家强?XX XX 找 Blue Fly . 说到 NDK 开发,其实麻烦的是配置。 在这里不用配置Cygwin ,不用额外操作;不使用 Eclipse ;使用最新的 Android St...
  • qiujuer
  • qiujuer
  • 2014年12月21日 12:01
  • 30020

AndroidStudio中的NDK开发初探

前段时间由于做比赛的事,一直都没时间写博客,现在终于可以补上一篇了,一直想学习一点NDK开发的知识,但是迟迟没有动手,正好有一个NDK相关的项目机会,便查阅了一些资料,遂将学习的一些心得方法记录于此。...
  • bingjianIT
  • bingjianIT
  • 2017年07月20日 17:40
  • 4063

android studio下的NDK开发详解(一)

好记性不如烂笔头,开始坚持写博客,学一点记一点,只为了生活更好。 学了一年多的硬件,现在来做android,不知道是对是错,跟着感觉走,开始总是想把android和硬件挂上勾,所以第一个android...
  • tuoguang
  • tuoguang
  • 2015年09月01日 01:05
  • 4679

Android studio NDK开发

Android Studio版本:release 1.0.2 创建一个空的project。创建一个空的activity。 在该类里面定义一个native方法。如下: public native Str...
  • rznice
  • rznice
  • 2014年12月31日 15:55
  • 58433

Android Studio下使用NDK

学习在Android Studio上使用NDK,花的时间比当时用ADT还长。呵呵,顺便吐槽一下,百度出来的资料不多,用微软的必应和雅虎的搜索比较多;另外搜索出来的很多链接是连接失败的,这个做Andro...
  • zhaoguangjun33
  • zhaoguangjun33
  • 2016年06月16日 10:37
  • 5888

Android Studio NDK基础使用

NDK是什么?Android平台是基于java实现,运行于虚拟机Dalvik;故而使用Android SDK创建应用程序需要使用java语言来编写实现。不过并不仅限于使用java,google在发布a...
  • dahaohan
  • dahaohan
  • 2016年03月31日 20:48
  • 2037

在Android Studio中NDK环境配置

Android Studio中NDK环境配置 第一种方法: 1.)打开AndroidStudio,选择顶部工具条,Tools->Android -> SDK Manager (需翻墙) ...
  • u012737144
  • u012737144
  • 2016年10月27日 11:07
  • 6391

Android Studio 2.2 NDK开发环境搭建

转载请标明出处:http://blog.csdn.net/shensky711/article/details/52763192 本文出自: 【HansChen的博客】 Android应用程序使...
  • shensky711
  • shensky711
  • 2016年10月09日 08:47
  • 11678
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Android Dev Intro - Android NDK with Android Studio
举报原因:
原因补充:

(最多只允许输入30个字)