21
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Android StudioでNDKを使ったビルドをする

Posted at

なかなかAndroid StudioがNDKサポートを追加しないので、gradleの仕組みを使ってとりあえずNDK対応してみる。
参考にしたのはOculus Mobile SDKのソース。

やり方

アプリのbuild.gradleに、次のコードを追加する。一番下とかで良いです。

// ANDROID_NDK_HOME
// ANDROID_NDK
// NDKROOT
// local.properties の ndk.dir
// の順にNDKのパスを検索して、ndk-buildのフルパスを取得する
def GetNDKBuildCmd() {

    def ndkDir = System.getenv('ANDROID_NDK_HOME')
    if (ndkDir == null) {
        ndkDir = System.getenv('ANDROID_NDK')
    }
    if (ndkDir == null) {
        ndkDir = System.getenv('NDKROOT')
    }
    if (ndkDir == null) {
        Properties properties = new Properties()
        properties.load(project.rootProject.file('local.properties').newDataInputStream())
        ndkDir = properties.getProperty('ndk.dir')
    }
    if (ndkDir == null) {
        throw new GradleException('NDK not found! Check your environment for ANDROID_NDK or your local.properties contains ndk.dir')
    }
    if (OperatingSystem.current().isWindows()) {
        return ndkDir + '/ndk-build.cmd'
    } else {
        return ndkDir + '/ndk-build'
    }
}

project.afterEvaluate {
    compileDebugNdk.dependsOn 'NDKBuildDebug'
    compileReleaseNdk.dependsOn 'NDKBuildRelease'
    clean.dependsOn 'NDKBuildClean'
}

task NDKBuildDebug(type: Exec) {
    commandLine GetNDKBuildCmd(), 'V=0', '-j10', 'NDK_DEBUG=1', 'OVR_DEBUG=1', "NDK_PROJECT_PATH=$projectDir/src/main"
}

task NDKBuildRelease(type: Exec) {
    commandLine GetNDKBuildCmd(), 'V=0', '-j10', 'NDK_DEBUG=0', 'OVR_DEBUG=0', "NDK_PROJECT_PATH=$projectDir/src/main"
}

task NDKBuildClean(type: Exec) {
    commandLine GetNDKBuildCmd(), 'clean', "NDK_PROJECT_PATH=$projectDir/src/main"
}

そして、android -> sourceSets -> main のブロック内にjniライブラリの設定を追加する。

android {
    ...

    sourceSets {
        main {
            jniLibs.srcDir 'src/main/libs'
            jni.srcDirs = [] // レガシー ndk-build サポートを無効にする
        }
    }
}

これで、Android Studioのビルドを走らせた時に ndk-build が呼ばれ、APKに含まれるようになります。

21
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?