LoginSignup
18
22

More than 5 years have passed since last update.

Android Studioでndkを使う

Posted at

久しぶりにndk触ろうと思ったら設定方法とか変わってたのでメモ. experimentalなプラグインを使うと便利. でもexperimentalなのでproductionに使う場合は注意.

環境

  • Mac OS X EI Capitan (10.11.6)
  • Android Studio 2.1.3

Android NDKのインストール

  1. Cmd+;で「Project Structure」画面を開き, 左のリストから一番上の「SDK Location」を選択.
  2. 「Android NDK Location」の「Download」を選択
  3. 10分ほどでインストール完了. 結構長い.

プロジェクトの設定を変更

gradle-wrapper.propertiesを変更

gradle-2.10を使うようにする. 2.10より新しくてもダメっぽい.

gradle-wrapper.properties
distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

build.gradle(Project)を変更

変更前

build.gradle
classpath 'com.android.tools.build:gradle:2.1.3'

変更後

build.gradle
classpath 'com.android.tools.build:gradle-experimental:0.7.0'

build.gradle (Module)を変更

以下のように書き換える. pluginが変わって書き方がだいぶ変更されている. minSdkVersiontargetSdkproguardFilesの記述方法も地味にも変わっている.
モジュール名helloでndkの設定も足しています.

build.gradle
apply plugin: 'com.android.model.application'

model {
    android {
        compileSdkVersion 23
        buildToolsVersion "24.0.1"

        defaultConfig {
            applicationId "com.yourdomain.appname"
            minSdkVersion.apiLevel = 19
            targetSdkVersion.apiLevel = 23
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles.add(file('proguard-android.txt'))
            }
        }
        ndk {
            moduleName = "hello"
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
}

Java/Cのコードを書く

MainActivityに以下のコードを追加.

MainActivity.java
    static {
        System.loadLibrary("hello");
    }

    public native String getMessage();

この時点ではnativeにgetMessage()がないのでエラーが出ています. getMessage()にカーソルを合わせalt-Enterを押し「create function...」を選ぶとnativeコードの雛形を生成してくれます. 生成されたコードが下記. ちょー便利!!!

hello.c
#include <jni.h>

JNIEXPORT jstring JNICALL
Java_com_yourdomain_appname_MainActivity_getMessage(JNIEnv *env, jobject instance) {
    // TODO
    return (*env)->NewStringUTF(env, returnValue);
}

returnValueが未実装でエラーが出ているので"hello world"と入れておきます.

hello.c
#include <jni.h>

JNIEXPORT jstring JNICALL
Java_com_yourdomain_appname_MainActivity_getMessage(JNIEnv *env, jobject instance) {
    return (*env)->NewStringUTF(env, "hello world");
}

これで、MainActivitygetMessage()が使えるようになりました!

18
22
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
18
22