Android studio, gradle and NDK
Asked Answered
C

23

157

I am very new to this whole gradle and Android Studio support. I have managed to convert my android project to gradle using the export option.

But I am looking for some documentation or start point how to integrate the NDK build into the gradle build process.

If possible I also need some sort of "after" stage that copies the build binaries (.so files) to the asset directory.

Cookhouse answered 21/5, 2013 at 10:35 Comment(8)
I have posted my answer in the below mentioned link #20901314Percyperdido
New readers: Be aware this question was initially asked during the Android Studio beta period; the answer has changed over time. Pay attention to the Gradle version mentioned in the answers, as well as when the answers were actually posted.Civet
If something really changes I will edit the question to relect the statusCookhouse
Android Studio 1.3 at canary channel fully supports NDK. Reference: tools.android.com/download/studio/canary/latestPecksniffian
June 18th, 2015: Android Studio 1.3 Beta is now available in the beta channel! Sorry, this build does not yet contain the C/C++ support; source: tools.android.com/recent/androidstudio13betaavailableViand
This solution is work, without code [Adding .so Library in Android Studio 1.0.2][1] [1]: #24358187Erikerika
@user1307559 That solution is not a solution for someone who needs to work with/compile the c/c++ filesCookhouse
Android Studio, gradle and NDK integration step by step ph0b.com/android-studio-gradle-and-ndk-integrationDictionary
G
86

We have released a first version of the integration as a preview in 1.3: http://tools.android.com/tech-docs/android-ndk-preview

The integration will stay a preview even after 1.3 becomes final. No current ETA as to when it'll be final (as of 2015/07/10).

More information here: http://tools.android.com/tech-docs/android-ndk-preview

Grampositive answered 22/5, 2013 at 1:40 Comment(15)
Would be great if I could use NDK and command completion with debugging under Android Studio (and Gradle support)Theorist
@GREnvoy - How do we configure the right NDK builder in Android studio ? Can you plz give me the steps ? :)Gaikwar
@Gaikwar - I used this tutorial to start software.intel.com/en-us/videos/…Biggers
@Gaikwar - I also created a new answer with more of what I did. I hope that helps.Biggers
@Gaikwar Much like GREnvoy, I've also created an answer with instructions on the new Android Studio: https://mcmap.net/q/48660/-android-studio-gradle-and-ndk This current answer was correct last May, but Android Studio has just built in NDK with Gradle in Android Studio, so some of the other answers are a bit more correct now...Component
Posted January 20th, 2015. I downvoted this answer because it is now outdated. Unfortunately, I have not found a reliable, updated answer. @Xavier, if you could point us in the right direction with a comment, or add a comment to the answer you feel is most appropriate, it would be much appreciated!Civet
@DirtyBeach Why is it outdated? There still isn't an integration of the NDK in Studio. We are working on it but no ETA at this time.Grampositive
My action was based upon how I was defining "integration". I understood it to mean "a way to use the NDK with gradle" which now does exist, albeit none of them are fantastic solutions. However, based on your comment, it seems your team has something else in mind for what a true integration could be. I retract my previous statement.Civet
NDK integration was announced during Google IO 2015. It's available in Android Studio 1.3 (preview can be downloaded soon. I'll post a link when it's available).Cowman
@CypressFrankenfeld: why does it say its in the stable channel when its not? where should it be? thanks!Wellfixed
It's not in the stable channel. It's in the canary channelCowman
Android-Studio 1.3 RC1 with NDK-Support is now available in the Canary-Channel sites.google.com/a/android.com/tools/download/studio/canary/…Viand
I have tried the 1.3 stable version, the native code debug still not workingSuperbomb
Downvoted. I must say that state of NDK integration is very frustrating. Even though integration was announced on Google I/O 2015, it's still not even close to be a production-ready solution with no ETA available. I understand that topic might be very complicated from the inside, but from the outside (from developer perspective) it just seems that Google does not care about NDK.Oniskey
This answer was correct at time of posting, but is pretty dated now - anyone reading this question should take note of the Android Studio versions.Component
C
44

UPDATE: The Android Studio with NDK support is out now: http://tools.android.com/tech-docs/android-ndk-preview

For building with a script the gradle solution below should work:

I am using my build script and added to my file (Seems to work for 0.8+): This seems to be equivalent to the solution below (but looks nicer in the gradle file):

 android {
    sourceSets {
        main {
            jniLibs.srcDirs = ['native-libs']
            jni.srcDirs = [] //disable automatic ndk-build
        }
    }
 }

The build unfortunately does not fail if the directory is not present or contains no .so files.

Cookhouse answered 28/5, 2013 at 11:16 Comment(10)
This does not work anymore with the new Android Studio version, workaround?Theorist
A bit of Groovy magic: tasks.withType(com.android.build.gradle.tasks.PackageApplication) { it.jniFolders = [file("libs")] as Set }. Thank you guys for help!Meister
What is the procedure for android Studio 0.8.9Supply
It should still work with Android 0.8.9. Note there is no real official nice solution (as in developing ndk from Android Studio).Cookhouse
But this doesnt work for me.. My tree is like this MyProj > -app> -native-libs> -armeabi-v7a> -a.so -b.so -c.soSupply
@plaisthos: can u show me the project structure, where can i keep these .so files. please.Supply
my structure is as you described. Double check what you are doing and that .so files really are not in the apk (unzip)Cookhouse
I confirm that the sourceSets solution works on AS 1.0.2. Thanks!Sanhedrin
@Cookhouse Thanks a lot for pointing out the right direction! The second line in the gradle script jni.srcDirs = [] //disable automatic ndk-build is very important since it will prevent Android Studio from rebuilding C/C++ source code. I have been trying to figure this out for two days until I saw your post and this solved my problem. I really think NDK build is better separately built by Android.mk command line makefile only, not by gradle script since C/C++ has been built by Makefile for more than 40 years!Gazette
Syntax highlighting, inline compiler broken with AS 2.0 update. See this, need help. #36567610Trifocals
C
41

With the update of Android Studio to 1.0, the NDK toolchain support improved immensely (note: please read my updates at the bottom of this post to see usage with the new experimental Gradle plugin and Android Studio 1.5).

Android Studio and the NDK are integrated well enough so that you just need to create an ndk{} block in your module's build.gradle, and set your source files into the (module)/src/main/jni directory - and you're done!

No more ndk-build from the command line.

I've written all about it in my blog post here: http://www.sureshjoshi.com/mobile/android-ndk-in-android-studio-with-swig/

The salient points are:

There are two things you need to know here. By default, if you have external libs that you want loaded into the Android application, they are looked for in the (module)/src/main/jniLibs by default. You can change this by using setting sourceSets.main.jniLibs.srcDirs in your module’s build.gradle. You’ll need a subdirectory with libraries for each architecture you’re targeting (e.g. x86, arm, mips, arm64-v8a, etc…)

The code you want to be compiled by default by the NDK toolchain will be located in (module)/src/main/jni and similarly to above, you can change it by setting sourceSets.main.jni.srcDirs in your module’s build.gradle

and put this into your module's build.gradle:

ndk {
  moduleName "SeePlusPlus" // Name of C++ module (i.e. libSeePlusPlus)
  cFlags "-std=c++11 -fexceptions" // Add provisions to allow C++11 functionality
  stl "gnustl_shared" // Which STL library to use: gnustl or stlport
}

That's the process of compiling your C++ code, from there you need to load it, and create wrappers - but judging from your question, you already know how to do all that, so I won't re-hash.

Also, I've placed a Github repo of this example here: http://github.com/sureshjoshi/android-ndk-swig-example

UPDATE: June 14, 2015

When Android Studio 1.3 comes out, there should be better support for C++ through the JetBrains CLion plugin. I'm currently under the assumption that this will allow Java and C++ development from within Android Studio; however I think we'll still need to use the Gradle NDK section as I've stated above. Additionally, I think there will still be the need to write Java<->C++ wrapper files, unless CLion will do those automatically.

UPDATE: January 5, 2016

I have updated my blog and Github repo (in the develop branch) to use Android Studio 1.5 with the latest experimental Gradle plugin (0.6.0-alpha3).

http://www.sureshjoshi.com/mobile/android-ndk-in-android-studio-with-swig/ http://github.com/sureshjoshi/android-ndk-swig-example

The Gradle build for the NDK section now looks like this:

android.ndk {
    moduleName = "SeePlusPlus" // Name of C++ module (i.e. libSeePlusPlus)
    cppFlags.add("-std=c++11") // Add provisions to allow C++11 functionality
    cppFlags.add("-fexceptions")
    stl = "gnustl_shared" // Which STL library to use: gnustl or stlport
}

Also, quite awesomely, Android Studio has auto-complete for C++-Java generated wrappers using the 'native' keyword:

Example of auto-complete of C++-Java wrapper

However, it's not completely rosy... If you're using SWIG to wrap a library to auto-generate code, and then try to use the native keyword auto-generation, it will put the code in the wrong place in your Swig _wrap.cxx file... So you need to move it into the "extern C" block:

C++-Java wrapper moved to correct location

UPDATE: October 15, 2017

I'd be remiss if I didn't mention that Android Studio 2.2 onwards has essentially 'native' (no pun) support for the NDK toolchain via Gradle and CMake. Now, when you create a new project, just select C++ support and you're good to go.

You'll still need to generate your own JNI layer code, or use the SWIG technique I've mentioned above, but the scaffolding of a C++ in Android project is trivial now.

Changes in the CMakeLists file (which is where you place your C++ source files) will be picked up by Android Studio, and it'll automatically re-compile any associated libraries.

Component answered 2/1, 2015 at 3:48 Comment(2)
put the *.so in (module)/src/main/jniLibsSanburn
why is NDEBUG always set when using Android Studio, even on debug buildsFlorentinoflorenza
C
35

In Google IO 2015, Google announced full NDK integration in Android Studio 1.3.

It is now out of preview, and available to everyone: https://developer.android.com/studio/projects/add-native-code.html

Old answer: Gradle automatically calls ndk-build if you have a jni directory in your project sources.

This is working on Android studio 0.5.9 (canary build).

  1. Download the NDK

  2. Either add ANDROID_NDK_HOME to your environment variables or add ndk.dir=/path/to/ndk to your local.properties in your Android Studio project. This allows Android studio to run the ndk automatically.

  3. Download the latest gradle sample projects to see an example of an ndk project. (They're at the bottom of the page). A good sample project is ndkJniLib.

  4. Copy the gradle.build from the NDK sample projects. It'll look something like this. This gradle.build creates a different apk for each architecture. You must select which architecture you want using the build variants pane. build variants pane

    apply plugin: 'android'
    
    dependencies {
        compile project(':lib')
    }
    
    android {
        compileSdkVersion 19
        buildToolsVersion "19.0.2"
    
        // This actual the app version code. Giving ourselves 100,000 values [0, 99999]
        defaultConfig.versionCode = 123
    
        flavorDimensions "api", "abi"
    
        productFlavors {
            gingerbread {
                flavorDimension "api"
                minSdkVersion 10
                versionCode = 1
            }
            icecreamSandwich {
                flavorDimension "api"
                minSdkVersion 14
                versionCode = 2
            }
            x86 {
                flavorDimension "abi"
                ndk {
                    abiFilter "x86"
                }
                // this is the flavor part of the version code.
                // It must be higher than the arm one for devices supporting
                // both, as x86 is preferred.
                versionCode = 3
            }
            arm {
                flavorDimension "abi"
                ndk {
                    abiFilter "armeabi-v7a"
                }
                versionCode = 2
            }
            mips {
                flavorDimension "abi"
                ndk {
                    abiFilter "mips"
                }
                versionCode = 1
            }
            fat {
                flavorDimension "abi"
                // fat binary, lowest version code to be
                // the last option
                versionCode = 0
            }
        }
    
        // make per-variant version code
        applicationVariants.all { variant ->
            // get the version code of each flavor
            def apiVersion = variant.productFlavors.get(0).versionCode
            def abiVersion = variant.productFlavors.get(1).versionCode
    
            // set the composite code
            variant.mergedFlavor.versionCode = apiVersion * 1000000 + abiVersion * 100000 + defaultConfig.versionCode
        }
    
    }
    

Note that this will ignore your Android.mk and Application.mk files. As a workaround, you can tell gradle to disable atuomatic ndk-build call, then specify the directory for ndk sources manually.

sourceSets.main {
    jniLibs.srcDir 'src/main/libs' // use the jni .so compiled from the manual ndk-build command
    jni.srcDirs = [] //disable automatic ndk-build call
}

In addition, you'll probably want to call ndk-build in your gradle build script explicitly, because you just disabled the automatic call.

task ndkBuild(type: Exec) {
   commandLine 'ndk-build', '-C', file('src/main/jni').absolutePath
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn ndkBuild
}
Cowman answered 6/6, 2014 at 13:49 Comment(7)
Yes. But that only works under Unix platforms and also limited if you a more complex than very simple ndk configuration/makefiles.Cookhouse
Yes, it will autogenerate makefiles for the limited things that you can set in the gradle build file, however there is a workaround. I added it to my answer.Cowman
The call to ndk-build will only work at the command-line not from within Android Studio.Wroth
Although this is not the most recent answer, it seems likely to be the most accurate. Pay special attention to step 3: "Download the latest gradle sample projects".Civet
@CameronLowellPalmer, did you add your NDK path to local.properties? ndk.dir=/path/to/ndkCowman
Of course. For some reason my comment now seems out of context. Not sure what I was referring to at the time. I actually have a very similar answer at #21097319.Wroth
I use this hack instead of disabling src dir so I can edit c/c++ files within the ide tasks.all { task -> if (task.name.contains('Ndk')) task.enabled = false }Zima
D
23

I found "gradle 1.11 com.android.tools.build:gradle:0.9.+" supports pre-build ndk now, you can just put the *.so in the dir src/main/jniLibs. when building gradle will package the ndk to the right place.

here is my project

Project:
|--src
|--|--main
|--|--|--java
|--|--|--jniLibs
|--|--|--|--armeabi
|--|--|--|--|--.so files
|--libs
|--|--other.jar
Derrik answered 13/5, 2014 at 1:39 Comment(0)
P
18

As Xavier said, you can put your prebuilts in /src/main/jniLibs/ if you are using gradle 0.7.2+

taken from: https://groups.google.com/d/msg/adt-dev/nQobKd2Gl_8/ctDp9viWaxoJ

Pinzler answered 2/1, 2014 at 15:30 Comment(2)
How can we see the sample mentiuoned in 0.7.2 ndkJniLib ?Inaptitude
Useful for using libraries such as SqlCipherVoroshilov
Z
16

As of now (Android Studio v0.8.6) it's quite simple. Here are the steps to create a "Hello world" type app:

  1. Download the Android NDK and put the root folder somewhere sane -- in the same location as the SDK folder, perhaps.

  2. Add the following to your local.properties file: ndk.dir=<path-to-ndk>

  3. Add the following to your build.gradle file inside of the defaultConfig closure, right after the versionName line: ndk { moduleName="hello-world" }

  4. In your app module's main directory, create a new folder called jni.

  5. In that folder, create a file called hello-world.c, which you'll see below.

  6. See the example Activity code below for an example of how to call a method (or is it a function?) in hello-world.c.


hello-world.c

#include <string.h>
#include <jni.h>

jstring
Java_me_mattlogan_ndktest_MainActivity_stringFromJNI(JNIEnv* env, jobject thiz)
{
    return (*env)->NewStringUTF(env, "Hello world!");
}

MainActivity.java

public class MainActivity extends Activity {

    static {
        System.loadLibrary("hello-world");
    }

    public native String stringFromJNI();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String testString = stringFromJNI();

        TextView mainText = (TextView) findViewById(R.id.main_text);
        mainText.setText(testString);
    }
}

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 20
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "me.mattlogan.ndktest"
        minSdkVersion 15
        targetSdkVersion 20
        versionCode 1
        versionName "1.0"

        ndk {
            moduleName "hello-world"
        }
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

Find the full source code of a very similar app here (minus the NDK).

Zany answered 16/8, 2014 at 23:45 Comment(4)
I'm doing exactly as instructed in my current project, but the NDK stuff still isn't getting built. Any ideas? It seems like it's building everything else, but just skipping the jni stuff.Noreennorene
@NannuoLei thanks, I tried but I am getting a problem where the .so are not being generated. Everything else seems to work, but when I run the apkg in the emulator, it complains it cannot load the shared object.Rechabite
@Rechabite is your emulator based on an x86 image? By default NDK will just produce an ARMEABI library, if you want to build an x86 image you can add this line into Application.mk: APP_ABI := armeabi x86Sanhedrin
it worked with me. PS: anyone seeing this answer, don't forget to change Java_me_mattlogan_ndktest_MainActivity_stringFromJNI to your own :)Lanner
P
8

If you're on unix the latest version (0.8) adds ndk-build. Here's how to add it:

android.ndk {
    moduleName "libraw"
}

It expects to find the JNI under 'src/main/jni', otherwise you can define it with:

sourceSets.main {
    jni.srcDirs = 'path'
}

As of 28 JAN 2014 with version 0.8 the build is broken on windows, you have to disable the build with:

sourceSets.main {
    jni.srcDirs = [] //disable automatic ndk-build call (currently broken for windows)
}
Psychopathology answered 28/1, 2014 at 14:26 Comment(5)
Is there any documentation to that feature? I could not find any. At the moment that seems to completly ignore my Android.mk/Application.mk.Cookhouse
I haven't found any. It may have snuck into the build half-baked. I'm on windows so I can only confirm that it fails on trying to call the unix ndk-build script. There'd be no other reason to call that then to integrate native compile in gradle. Are you in unix?Psychopathology
See #20675150Lowercase
it actually expects to find prebuilt *.so files in jniLibs.srcDirsPenick
I'd disagree based on the fact that it crashes calling ndk-build which absolutely isn't necessary if it requires built libraries. I cannot confirm since I don't have the time to vm Linux right now.Psychopathology
F
7

An elegant workaround is shown in https://groups.google.com/d/msg/adt-dev/nQobKd2Gl_8/Z5yWAvCh4h4J.

Basically you create a jar which contains "lib/armeabi/yourlib.so" and then include the jar in the build.

Farina answered 12/8, 2013 at 13:13 Comment(2)
Yeah. That only works well if you don't change your code native often. And you will have to include binary jar files in the repository. Otherwise you end up with a build script that creates a jar on fly.Cookhouse
I've modified Android's Hello-JNI example with a simple bash script that wraps ndk-build, generates .jars for each .so and places them in gradle's build path to ease this pain. Check it out.Mcclung
E
4

A good answer automating the packaging of readily compiled .so-files is given in another (closed) thread. To get that working, I had to change the line:

from fileTree(dir: 'libs', include: '**/*.so')

into:

from fileTree(dir: 'src/main/libs', include: '**/*.so') 

Without this change the .so files were not found, and the task for packaging them would therefore never run.

Eglantine answered 21/10, 2013 at 11:3 Comment(1)
Update: please note that in the newer Android Studios (at least in 1.5) the native code is much better incorporated, and it is not necessary to do this separate task for packaging your code.Eglantine
A
4

The answer from @plaisthos broke in the latest gradle version, but there is still a way to do it. Create a native-libs directory in the root of your project directory and copy all y our libs into this directory.

Add the following lines to your build.gradle. Build and be happy.

task copyNativeLibs(type: Copy) {
    from(new File(project(':<your project>').getProjectDir(), 'native-libs')) { include '**/*.so' }
    into new File(buildDir, 'native-libs')
}

tasks.withType(Compile) { compileTask -> compileTask.dependsOn copyNativeLibs }

clean.dependsOn 'cleanCopyNativeLibs'
Anvers answered 24/12, 2013 at 1:44 Comment(0)
P
3

This is the code i use to build using android-ndk from gradle. For this add ndk directory path in gradle.properties ie . add ndkdir=/home/user/android-ndk-r9d and put all jni files in a folder native in src/main/ as you can see from code posted below. It will create jar with native libs which you can use normally as in System.loadLibrary("libraryname");

dependencies {
    compile fileTree(dir: "$buildDir/native-libs", include: '*.jar')
}

task ndkBuild(type: Exec) {
    commandLine "$ndkdir/ndk-build", "--directory", "$projectDir/src/main/native", '-j', Runtime.runtime.availableProcessors(),
            "APP_PLATFORM=android-8",
            "APP_BUILD_SCRIPT=$projectDir/src/main/native/Android.mk",
            "NDK_OUT=$buildDir/native/obj",
            "NDK_APP_DST_DIR=$buildDir/native/libs/\$(TARGET_ARCH_ABI)"
}

task nativeLibsToJar(type: Jar, description: 'create a jar with native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    from fileTree(dir: "$buildDir/native/libs", include: '**/*.so')
    into 'lib/'
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn nativeLibsToJar
}

nativeLibsToJar.dependsOn 'ndkBuild'
Presley answered 17/6, 2014 at 17:24 Comment(0)
P
3

I have used the following code to compile native dropbox libraries, I am using Android Studio v1.1.

task nativeLibsToJar(type: Zip) {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    extension 'jar'
    from fileTree(dir: 'src/main/libs', include: '**/*.so')
    into 'lib/'
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn(nativeLibsToJar)
}
Pyrite answered 1/5, 2015 at 10:57 Comment(0)
I
2

I have used ndk.dir=/usr/shareData/android-ndk-r11b // path of ndk

in local.properties file in android studio project. and add this line :
android.useDeprecatedNdk=true

in gradle.properties file in android studio project.

More information here: http://tools.android.com/tech-docs/android-ndk-preview

Itch answered 27/3, 2016 at 21:1 Comment(0)
P
1

To expand on what Naxos said (Thanks Naxos for sending me in the right direction!), I learned quite a bit from the recently released NDK examples and posted an answer in a similar question here.

How to configure NDK with Android Gradle plugin 0.7

This post has full details on linking prebuilt native libraries into your app for the various architectures as well as information on how to add NDK support directly to the build.gradle script. For the most part, you shouldn't need to do the work around zip and copy anymore.

Phobia answered 30/1, 2014 at 5:21 Comment(0)
I
1

configure project in android studio from eclipse: you have to import eclipse ndk project to android studio without exporting to gradle and it works , also you need to add path of ndk in local.properties ,if shows error then add

sourceSets.main {
        jniLibs.srcDir 'src/main/libs' 
        jni.srcDirs = [] //disable automatic ndk-build callenter code here
    }

in build.gradle file then create jni folder and file using terminal and run it will work

Irade answered 3/11, 2014 at 7:37 Comment(1)
See see my own answer. That is the workaround I am currently using but it is not really a solution.Cookhouse
B
1

Here are the steps that I used to get the NDK working in my Android Studio project. I used this tutorial to help me out https://software.intel.com/en-us/videos/using-the-ndk-with-android-studio

In order to use NDK you must add a NDK line to local.properties. So under your sdk.dir add

ndk.dir=C\:\\MyPathToMyNDK\ndk

In my apps build.gradle I have the following code

        ndk {
            moduleName "myLib"
            ldLibs "log"
            stl "gnustl_shared"
            cFlags "-std=c++11 -frtti -fexceptions -pthread"
        }

moduleName is the name you want to give your native code. I believe this is what the shared library will be called. ldLibs allows me to log to LogCat, stl is the stl that you want to import. There are lots of options, same as the Eclipse NDK. (http://www.kandroid.org/ndk/docs/CPLUSPLUS-SUPPORT.html)

cFlags are still a certain amount of black magic for me. I have not found a good source for all the options and what they give me. Search around StackOverflow for anything you need, that is where I found it. I do know that the c++11 allows me to use the new c++ 11 standard.

Here is an example of how I log to LogCat from the native code

__android_log_print(ANDROID_LOG_DEBUG, "TestApp", "Adding - String %d has a field name of %s and a value of %s", i, lKeyUTF8.c_str(), lValueUTF8.c_str());
Biggers answered 15/12, 2014 at 13:13 Comment(0)
C
1

Now that Android Studio is in the stable channel, it is pretty straightforward to get the android-ndk samples running. These samples use the ndk experimental plugin and are newer than the ones linked to from the Android NDK online documentation. Once you know they work you can study the build.gradle, local.properties and gradle-wrapper.properties files and modify your project accordingly. Following are the steps to get them working.

  1. Go to settings, Appearance & Behavior, System Settings, Android SDK, selected the SDK Tools tab, and check Android NDK version 1.0.0 at the bottom of the list. This will download the NDK.

  2. Point to the location of the newly downloaded NDK. Note that it will be placed in the sdk/ndk-bundle directory. Do this by selecting File, Project Structure, SDK Location (on left), and supplying a path under Android NDK location. This will add an ndk entry to local.properties similar to this:

    Mac/Linux: ndk.dir=/Android/sdk/ndk-bundle
    Windows: ndk.dir=C:\Android\sdk\ndk-bundle

I have successfully built and deployed all projects in the repository this way, except gles3gni, native-codec and builder. I'm using the following:

Android Studio 1.3 build AI-141.2117773
android-ndk samples published July 28, 2015 (link above)
SDK Tools 24.3.3
NDK r10e extracted to C:\Android\sdk\ndk-bundle
Gradle 2.5
Gradle plugin 0.2.0
Windows 8.1 64 bit

Curlpaper answered 4/8, 2015 at 23:53 Comment(0)
W
1

NDK Builds and gradle (basic)

Generally building with the NDK is as simple as correctly specifying an ndkBuild path to Android.mk or cmake path to CMakeLists.txt. I recommend CMake over the older Android.mk because Android Studio's C/C++ support is based upon CLion and it uses CMake as its project format. This in my experience has tended to make the IDE more responsive on larger projects. Everything compiled in your project will be built and copied into the APK automatically.

apply plugin: 'com.android.library'

android {
    compileSdkVersion 19
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 19

        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', 'x86'
            // 64-bit support requires an Android API level higher than 19; Namely 21 and higher
            //abiFilters 'armeabi', 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
        }

        externalNativeBuild {
            cmake {
                arguments '-DANDROID_TOOLCHAIN=clang',
                        '-DANDROID_PLATFORM=android-19',
                        '-DANDROID_STL=gnustl_static',
                        '-DANDROID_ARM_NEON=TRUE'

            }
        }
    }

    externalNativeBuild {
        cmake {
            path 'src/main/jni/CMakeLists.txt'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

Adding prebuilt libraries to the project (advanced)

Static libraries (.a) in your NDK build will automatically be included, but prebuilt dynamic libraries (.so) will need to be placed in jniLibs. This can be configured using sourceSets, but you should adopt the standard. You DO NOT NEED any additional commands in build.gradle when including prebuilt libraries.

The layout of jniLibs

You can find more information about the structure in the Android Gradle Plugin User Guide.

|--app:
|--|--build.gradle
|--|--src:
|--|--|--main
|--|--|--|--java
|--|--|--|--jni
|--|--|--|--|--CMakeLists.txt
|--|--|--|--jniLibs
|--|--|--|--|--armeabi
|--|--|--|--|--|--.so Files
|--|--|--|--|--armeabi-v7a
|--|--|--|--|--|--.so Files
|--|--|--|--|--x86
|--|--|--|--|--|--.so Files

You can then validate the resulting APK contains your .so files, typically under build/outputs/apk/, using unzip -l myApp.apk to list the contents.

Building shared libraries

If you're building a shared library in the NDK you do not need to do anything further. It will be correctly bundled in the APK.

Wroth answered 28/1, 2017 at 7:40 Comment(0)
M
0

Just add this lines to app build.gradle

dependencies {
    ...
    compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')
}

task nativeLibsToJar(type: Zip, description: 'create a jar archive of the native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    extension 'jar'
    from fileTree(dir: 'libs', include: '**/*.so')
    into 'lib/armeabi/'
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn(nativeLibsToJar)
}
Misanthrope answered 31/7, 2014 at 19:16 Comment(1)
I think the jniLibs.srcDirs approach is cleaner than this since you can use abiFilter/flavours but your approach should also work.Cookhouse
V
0

now.I can load the so success!

1.add the .so file to this path

Project:

|--src |--|--main |--|--|--java |--|--|--jniLibs |--|--|--|--armeabi |--|--|--|--|--.so files

2.add this code to gradle.build

android {
splits {
    abi {
        enable true
        reset()
        include 'x86', 'x86_64', 'arm64-v8a', 'armeabi-v7a', 'armeabi'
        universalApk false
    }
}

}

3.System.loadLibrary("yousoname");

  1. goodluck for you,it is ok with gradle 1.2.3
Vestibule answered 7/7, 2015 at 12:26 Comment(0)
E
0
  1. If your project exported from eclipse,add the codes below in gradle file:

    android {
       sourceSets{
            main{
               jniLibs.srcDir['libs']  
          }  
        }
    }
    

2.If you create a project in Android studio:

create a folder named jniLibs in src/main/ ,and put your *.so files in the jniLibs folder.

And copy code as below in your gradle file :

android {
    sourceSets{  
       main{  
         jniLibs.srcDir['jniLibs']  
      }  
    }
}
Elecampane answered 31/5, 2016 at 9:37 Comment(0)
A
0

While I believe SJoshi (oracle guy) has the most complete answer, the SWIG project is a special case, interesting and useful one, at that, but not generalized for the majority of projects that have done well with the standard SDK ant based projects + NDK. We all would like to be using Android studio now most likely, or want a more CI friendly build toolchain for mobile, which gradle theoretically offers.

I've posted my approach, borrowed from somewhere (I found this on SO, but posted a gist for the app build.gradle: https://gist.github.com/truedat101/c45ff2b69e91d5c8e9c7962d4b96e841 ). In a nutshell, I recommend the following:

  • Don't upgrade your project to the latest gradle build
  • Use com.android.tools.build:gradle:1.5.0 in your Project root
  • Use com.android.application in your app project
  • Make sure gradle.properties has: android.useDeprecatedNdk=true (in case it's complaining)
  • Use the above approach to ensure that your hours and hours of effort creating Android.mk files won't be tossed away. You control which targets arch(s) to build. And these instructions are kind to Windows users, who should theoretically be able to build on windows without special issues.

Gradle for Android has been a mess in my opinion, much as I like the maven concepts borrowed and the opinionated structure of directories for a project. This NDK feature has been "coming soon" for almost 3+ years.

Atbara answered 12/6, 2016 at 3:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.