LoginSignup
41

More than 5 years have passed since last update.

Andriod NDK Sample with Android Studio 1.0

Posted at

はじめに


Android Studio 1.0がリリースされ、GoogleからもAndroid StudioがofficalなAndroid用IDEであるとアナウンスされました。今まで、Eclipse + ADTでJNIを使ったアプリケーションを開発していましたが、今後のサポートの先行きが不透明なため、Android Studio でもNDKを動かしてみようと試行錯誤したメモをまとめました。

注意点

この作業を行っている際にGradle Consoleに

console
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.

とたくさん出力されるので、この情報が役に立たなくなるかもしれないので、できるだけソース元を参照するようにしてください。

demo movie

まずは、次のデモをご覧になるのがいいと思います。これで、おおまかな流れを掴んでください。

ここでは、このデモにしたがってsampleを作成しようとしましたがつまずいたところをノートしていきます。

local.properties

ndkのインストール先を設定する必要があります。

local.properties
sdk.dir=/Users/accountname/android-sdk/sdk
ndk.dir=/Users/accountname/android-ndk-r10d

build.gradle

http://ph0b.com/android-studio-gradle-and-ndk-integration/ にあります build.gradleのtemplateを用いようとしましたが、

console
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:ndkBuild'.
> A problem occurred starting process 'command 'ndk-build''

ndk-build が見つからないといわれ失敗します。 http://blog.gaku.net/ndk/ を参考にしますと、どうやらndk-buildをfull pathで指定しないといけないようです。そこで、ndk-build に関連する task ndkBuild を以下のように修正してみました(Windows環境ではテストしていないので、これで上手くいくかどうか教えていただけたらと思います)

build.gradle
// call regular ndk-build(.cmd) script from app directory
task ndkBuild (type: Exec) {
    def ndkBuildPath = project.plugins.findPlugin('com.android.application').getNdkFolder().absolutePath + File.separator
    if (Os.isFamily(Os.FAMILY_WINDOWS)) {
        ndkBuildPath += 'ndk-build.cmd'
    } else {
        ndkBuildPath += 'ndk-build'
    }
    commandLine ndkBuildPath, '-C', file('src/main').absolutePath
}

native method の定義

このデモでは、Activity class上にnative methodを定義して実装しています。しかし、Support Libraryの依存関係を考えると別途NDK用Manager classを定義して、native methodはすべてNDKManagerクラスを参照する方がラクだと思います。

このようにしますとjni用headerを作成するのがラクです。

console
> javah -d jni_2 -classpath ../../build/intermediates/classes/fat/debug/ com.example.ndksample_with_androidstudio.NDKManager 

(classpathの場所は適時環境に応じで変更してください。私はfatという名前ですべてのarchに対応したapkファイルを作成しようとしているので、fatという名のdirectoryが含まれています。)

sample

最後に、今回作成したProjectをgithub上(https://github.com/abekatsu/NDKSample_with_AndroidStudio
) で公開してますので参考にしていただけたらと思います。

References

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
41