Android Studio基础之编译JNI(七)-学习篇

9 篇文章 0 订阅
8 篇文章 0 订阅

这篇里学习下如何使用NDK来编译项目里的JNI工程。要使用NDK首先我们来配置好NDK的路径。
NDK
再来,打开项目中的local.properties文件看看,这个文件作为本地的一个配置文件,可以不纳入项目管理中。

## This file is automatically generated by Android Studio.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Thu Dec 24 16:17:15 CST 2015
ndk.dir=D\:\\Tools\\Android-SDK\\ndk-bundle
sdk.dir=D\:\\Tools\\Android-SDK

设置好后我们就可以开始编写相应的代码了,这里我先在工程里添加了如下的代码做为测试。

package eric.test;

/**
 * Created by Eric on 2015/12/24.
 */
public class TestNative {
    public static native String getHelloWorld();

    static {
        System.loadLibrary("testNative");
    }
}

很简单的,里面只声明了一个JNI方法getHelloWorld。
好了,先来编译一下,这样做的目的为class TestNative 生成相应的.class文件。然后我们来生成相应的C/C++的头文件,在项目的app module根目录执行如下的命令。

javah -classpath .\build\intermediates\classes\full\debug -d jni -jni eric.test.TestNative

-classpath 生成的.class所在路径。注意,这里.class是在包名的目录下,我们写的路径不包含包名的路径
-d 生成的.h文件所在路径
-jni 完整的class名
NDK

查看工程下面,是不是生成了相应的.h文件。
.h

在jni目录下新增一个.cpp文件,并实现.h中的方法。
这里写图片描述

打开app module中的build.gradle文件,在defaultConfig中添加如下内容

ndk {
    moduleName "testNative"
    abiFilters "armeabi"
}

moduleName : jni模块的模块名,loadlibrary中使用的名字
abiFilters :对应的APP_ABI

当上面的步骤完成后,我们就可以开始编译了,这里我们并不需要再去编写Anroid.mk或Application.mk文件了,Android Studio会自动去帮我们生成。
如下图中所示,我们可以在build/intermediates/ndk看到生成的内容。APK中也会自动打包进去。
.mk

编译时可能会出现如下的错误:

Error:(27, 1) A problem occurred evaluating project ':app'.
> Error: NDK integration is deprecated in the current plugin.  Consider trying the new experimental plugin.  For details, see http://tools.android.com/tech-docs/new-build-system/gradle-experimental.  Set "android.useDeprecatedNdk=true" in gradle.properties to continue using the current NDK integration.

需要在项目中的gradle.properties文件内,添加如下内容。

android.useDeprecatedNdk=true

另外,注意看我们编译时会有这样的提示,目前Android Studio对ndk的支持还不完整。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值