AndroidStudio NDK开发

来源:互联网 发布:ubuntu16.04 ssd 优化 编辑:程序博客网 时间:2024/05/29 20:00

参考链接:http://tools.android.com/tech-docs/new-build-system/gradle-experimental
环境介绍:AndroidStudio2.1.2,NDK R12
抛弃之前的生成头文件那种方法,让AndroidStudio自己生成所需的文件,只需关注你所需要的逻辑代码即可

新建工程

初始gradle如下:

apply plugin: 'com.android.application'android {    compileSdkVersion 23    buildToolsVersion "23.0.3"    defaultConfig {        applicationId "com.example.user.jnisample"        minSdkVersion 15        targetSdkVersion 23        versionCode 1        versionName "1.0"    }    buildTypes {        release {            minifyEnabled false            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'        }    }}dependencies {    compile fileTree(dir: 'libs', include: ['*.jar'])    testCompile 'junit:junit:4.12'    compile 'com.android.support:appcompat-v7:23.4.0'}

注意:这时候用的gradle为https://services.gradle.org/distributions/gradle-2.10-all.zip

project的gradle配置为:

// Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {    repositories {        jcenter()    }    dependencies {        classpath 'com.android.tools.build:gradle:2.1.2'        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}allprojects {    repositories {        jcenter()    }}task clean(type: Delete) {    delete rootProject.buildDir}

修改gradle配置文件

修改project的gradle文件

在project的gradle文件中修改gradle plugin为

com.android.tools.build:gradle-experimental:0.7.0-alpha4

注意:修改以后得project gradle文件如下:

// Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {    repositories {        jcenter()    }    dependencies {        classpath 'com.android.tools.build:gradle-experimental:0.7.0-alpha4'// 注意修改的是这个地方        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}allprojects {    repositories {        jcenter()    }}task clean(type: Delete) {    delete rootProject.buildDir}

修改完同步一下gradle,注意报错信息

Error:(1, 0) Plugin with id 'com.android.application' not found.<a href="openFile:D:\test\JNISample\app\build.gradle">Open File</a>

修改model的gradle文件

根据提示修改model的gradle文件:

apply plugin: 'com.android.application'

修改为:

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

然后继续同步,注意报错信息:

Error:(3, 0) Gradle DSL method not found: 'android()'Possible causes:<ul><li>The project 'JNISample' may be using a version of the Android Gradle plug-in that does not contain the method (e.g. 'testCompile' was added in 1.1.0).<a href="fixGradleElements">Fix plugin version and sync project</a></li><li>The project 'JNISample' may be using a version of Gradle that does not contain the method.<a href="openGradleSettings">Gradle settings</a></li><li>The build file may be missing a Gradle plugin.<a href="apply.gradle.plugin">Apply Gradle plugin</a></li>

注意Gradle DSL method not found: ‘android()’,找到原因之后继续修改文件:

apply plugin: 'com.android.model.application'model {//添加model根节点    android {        compileSdkVersion 23        buildToolsVersion "23.0.3"        defaultConfig {            applicationId "com.example.user.jnisample"            minSdkVersion 15            targetSdkVersion 23            versionCode 1            versionName "1.0"        }        buildTypes {            release {                minifyEnabled false                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'            }        }    }}dependencies {    compile fileTree(dir: 'libs', include: ['*.jar'])    testCompile 'junit:junit:4.12'    compile 'com.android.support:appcompat-v7:23.4.0'}

继续同步,注意报错Error:Cause: org.gradle.api.internal.ExtensibleDynamicObject

原因是因为更换后的gradle plugin语法为compileSdkVersion = 23,找到原因之后继续修改:

apply plugin: 'com.android.model.application'model {    android {        compileSdkVersion = 23        buildToolsVersion = "23.0.3"        defaultConfig {            applicationId = "com.example.user.jnisample"            minSdkVersion.apiLevel = 15 // 注意这里的修改            targetSdkVersion.apiLevel = 23            versionCode = 1            versionName = "1.0"        }        buildTypes {            release {                minifyEnabled false                proguardFiles.add(file('proguard-android.txt'))//注意这里的修改            }        }    }}dependencies {    compile fileTree(dir: 'libs', include: ['*.jar'])    testCompile 'junit:junit:4.12'    compile 'com.android.support:appcompat-v7:23.4.0'}

重新同步,离胜利仅有一部之遥了:

Error:Exception thrown while executing model rule: NdkComponentModelPlugin.Rules#createNativeBuildModel

错误提示是在执行model的gradle文件时,NDK模块rules有问题,原因是因为我们没有加NDK的rules,好了,加上下面的配置代码:

ndk {            moduleName = 'jniSimple'//这个名字是以后在代码中加载lib时候的名字System.loadLibrary("jniSimple");            toolchain = 'clang'            CFlags.addAll(['-Wall'])}

重新同步之后,如果你已经配置了NDK的路径,到此已经成功了,如果没有配置路径,自己设置一下NDK的路径就可以了
最终的model gradle文件如下:

apply plugin: 'com.android.model.application'model {    android {        compileSdkVersion = 23        buildToolsVersion = "23.0.3"        defaultConfig {            applicationId = "com.example.user.jnisample"            minSdkVersion.apiLevel = 15            targetSdkVersion.apiLevel = 23            versionCode = 1            versionName = "1.0"        }        ndk {            moduleName = 'jniSimple'            toolchain = 'clang'            CFlags.addAll(['-Wall'])        }        buildTypes {            release {                minifyEnabled false                proguardFiles.add(file('proguard-android.txt'))            }        }    }}dependencies {    compile fileTree(dir: 'libs', include: ['*.jar'])    testCompile 'junit:junit:4.12'    compile 'com.android.support:appcompat-v7:23.4.0'}

是时候让AndroidStudio自己生成C文件了

package com.example.user.jnisample;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    private native String getName();    static {        System.loadLibrary("jniSimple");    }}

如上代码,这时候getName()应该是红色状态,这是因为没有相应的jni方法与之对应,好了,我们要开始生成jni方法了:
这里写图片描述

将光标移动到getName()上,然后按下alt+enter组合键,就会弹出如图所示的框了,点击第一个Create,就能生成对应的jni方法,如果失败,请点击快捷工具栏中的同步gradle按钮这里写图片描述

然后重新生成jni方法

生成的jni方法如下:

#include <jni.h>JNIEXPORT jstring JNICALLJava_com_example_user_jnisample_MainActivity_getName(JNIEnv *env, jobject instance) {    // TODO    return (*env)->NewStringUTF(env, returnValue);}
0 0