NDK With Android Studio

AUG 17TH, 2014

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, usegradleto 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[project_root]/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 forarm64-v8a,x86-64andmips64.

This is how it looks like from Android Studio:
NDK With Android Studio_第1张图片

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

12
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.srcDirsin your module’sbuild.gradle:

12345678
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. Addndk.dirvariable inside thelocal.propertiesfile.
  2. Configurendkmodule 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 calledlocal.properties. Add andk.dirvariable directing to your ndk folder. For example:

12
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’sbuild.gradlefile locate your android’sdefaultConfigsection and add the following:

123
ndk {  moduleName "moduleNameHere" } 

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

Here is mine for reference:

12345678910111213141516171819
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 ascFlags,stlandldLibs.

123456
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 thisbad_function:

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

And gradle responded with:

NDK With Android Studio_第2张图片

Changing the folder of your source files

Just like with thejniLibsfolder, you can tell gradle to look for your C++ files in a different path. I for example prefer my source code insidesource. I can set it by editing thesourceSets.main.jni.srcDirsvariable:

12345678
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 theproductFlavorssection underandroidin the module’sbuild.gradlefile.

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 theabiFiltervariable:

1234567891011121314151617181920212223
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 defaultcFlagsand other settings here, just add them inside thendksection 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 :)

Aug 17th, 2014



来源 http://www.shaneenishry.com/blog/2014/08/17/ndk-with-android-studio/

更多相关文章

  1. Android在Button按钮上同时显示文字和图片
  2. Android如何使用XML创建一个环形渐变颜色图片
  3. Android 旋转图片
  4. Android 获取网络图片
  5. Android 图片加载缓存
  6. Android 系统图片
  7. 图片压缩
  8. Android三种方法设置ImageView的图片
  9. Android 如何加载大图片

随机推荐

  1. Android魔术——手把手教你实现水晶球波
  2. Android实现pppoe拨号上网(一)概述
  3. 给小白分享几个学习Android的网站
  4. android从程序员到架构师之路----高焕堂
  5. Android单线程模型相关概念详解
  6. android游戏开发(三)触屏事件处理_手势识
  7. Android中的MVP架构初探
  8. Android中Intent,service,broadcast应用浅
  9. 为什么 Android 截屏需要 root 权限
  10. android——Include进来的GridView无法显