Android Studio使用JNI

配置好你的环境

配置好ndk版本,要与Android编译版本相对应。 比如Android5.1的编译版本需要用r10d的ndk,用r9d会报错。

编写native方法

新建一个Module,然后创建一个类,在类中写好native方法

public class NDKString {
    public static native String getFormC();
}  

然后编译一下(此时会在build.intermediates\classes\debug目录下生产NDKString类)

生成.h文件

用cmd进入到Module的main目录层,然后执行以下命令

javah -d jni -classpath ..\..\build\intermediates\classes\debug Module的包名.类名  

比如

javah -d jni -classpath ..\..\build\intermediates\classes\debug com.ethanco.mylibrary.NDKString

然后就会生产jni目录及名为com_ethanco_mylibrary_NDKString.h的头文件

新建c文件

新建一个文件Hello.c,include com_ethanco_mylibrary_NDKString.h,并复制其方法进行实现。

#include "com_ethanco_mylibrary_NDKString.h"  
JNIEXPORT jstring JNICALL Java_com_ethanco_mylibrary_NDKString_getFormC  
  (JNIEnv * env, jclass jclass){  
    return (*env)->NewStringUTF(env,"From C");  
}    

进行编译

此时就可以编译了,但是会提示错误

Error:Execution failed for task ':mylibrary:compileDebugNdk'.  
> 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  

然后编译,发现还有错误

Error:Execution failed for task ':mylibrary:compileReleaseNdk'.  
> com.android.ide.common.process.ProcessException:  
org.gradle.process.internal.ExecException: Process 'command  
'F:\BaiduYunDownload\android-ndk-r10d\ndk-build.cmd'' finished with non-zero exit value 2   

这是Window的一个Bug,需要至少两个c文件件才可以,此处,我们在jni文件夹下在新建一个Hello1.c,无需写内容,然后再编译即可通过。

加载so

public class NDKString {
    static{
        System.loadLibrary("mylibrary"); //去掉开头的lib和结尾的.so
    }

    public static native String getFormC();
}

进行调用

通过NDKString.getFormC()即可调用

相关源码

http://download.csdn.net/detail/ethanco/9515008

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

氦客

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值