Android Studio使用JNI
16lz
2021-01-23
配置好你的环境
配置好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();}
相关源码
http://download.csdn.net/detail/ethanco/9515008
更多相关文章
- MPAndroidChart的一些问题解决方法
- 解决IE apk变成zip:Android 手机应用程序文件下载服务器 配置解决
- Android EditText TextWatcher 回调方法参数说明
- Android生成界面的两种方法:setContentView和inflate的区别
- Android 使用Canvas在图片上绘制文字的方法
- Android 项目快速更改包名的方法
- 『ANDROID』 在Android开发过程中,常Android 更新UI的两种方法—