JNI
来源:互联网 发布:mysql update 索引 编辑:程序博客网 时间:2024/06/03 16:37
最近有个新需求,需要把一些东西通过c++来实现,因此也接触到了NDK开发,此文章用于记录通过Android Studio开发NDK的基本流程,已经碰到的一些坑。
搭建NDK环境
要进行NDK开发,首先需要搭建DNK环境。
第一步,配置NDK SDK路径,打开项目配置设置SDK Location
第二步,定义3个宏命令,便于我们进行NDK开发时编译
定义宏命令的步骤如下图,在Preferences里打开External Tools进行配置
1.javah:这个命令的作用就是根据java类里面定义的native函数生成C/C++对应的.h文件
2.ndk-build,就是对应jni项目进行编译,生成对应的so库
3.ndk-clean,清理jni项目,清除生成的so库
当创建完之后,就可以在jni项目中使用了(注意是右键jni文件夹)
NDK开发实践
创建一个CommentUtils的类,在其中定义一个signCommentParams的native方法
package com.example.forone.nativedemo;public class CommentUtils { //加载so库 static { System.loadLibrary("CommentUtils"); } //定义一个native方法 public native static String signCommentParams(String params);}
然后右键CommentUtils这个类,选择External Tools → javah命令,此时会在jni文件夹中生成一个com_example_forone_nativedemo_CommentUtils.h。注意,此时可能会提示“错误: 找不到 ‘com.example.forone.nativedemo.CommentUtils’ 的类文件。”,这时只需要build一下项目就解决了。
/* DO NOT EDIT THIS FILE - it is machine generated */#include <jni.h>/* Header for class com_example_forone_nativedemo_CommentUtils */#ifndef _Included_com_example_forone_nativedemo_CommentUtils#define _Included_com_example_forone_nativedemo_CommentUtils#ifdef __cplusplusextern "C" {#endif/* * Class: com_example_forone_nativedemo_CommentUtils * Method: signCommentParams * Signature: (Ljava/lang/String;)Ljava/lang/String; */JNIEXPORT jstring JNICALL Java_com_example_forone_nativedemo_CommentUtils_signCommentParams (JNIEnv *, jclass, jstring);#ifdef __cplusplus}#endif#endif
然后在jni文件夹中创建CommentUtils.cpp文件,在这里对signCommentParams native函数进行实现。
#include "com_example_forone_nativedemo_CommentUtils.h" //对应signCommentParams JNIEXPORT jstring JNICALL Java_com_sogou_toptennews_commentnative_CommentUtils_signCommentParams (JNIEnv * env, jclass clazz, jstring jsParams){ return jsParams; };
修改app/build.gradle文件
defaultConfig { applicationId "com.example.forone.nativedemo" minSdkVersion 14 targetSdkVersion 21 versionCode 1 versionName "1.0" ndk { moduleName "CommentUtils" //配置名称 } }
修改gradle.properties,添加下面代码
android.useDeprecatedNdk= true
在jin目录下创建Android.mk文件
LOCAL_PATH := $(call my-dir)include $(CLEAR_VARS)LOCAL_LDLIBS := -lm -llog LOCAL_MODULE := CommentUtils //配置名称LOCAL_SRC_FILES := CommentUtils.cpp MD5.cpp //配置用到的C/C++源文件include $(BUILD_SHARED_LIBRARY)
在jin目录下创建Application.mk文件
APP_MODULES := CommentUtils //配置名称APP_ABI := all //配置对应的架构,这里是所有abi架构都支持APP_STL := stlport_static
选择jni目录右键,选择External Tools → ndk-build命令,生成对应的so库
至此,JNI开发的基本流程就介绍完了。
- Jni
- JNI
- JNI
- JNI
- JNI
- JNI
- JNI
- JNI
- JNI
- JNI
- JNI
- JNI
- JNI
- JNI
- JNI
- JNI
- JNI
- JNI
- 链表Java实现
- Linux
- c++ Primer 5 12.1.6节练习 (头文件相互包含的问题及解决办法)
- Unity3D Shader之路 写Shader前必须要知道的事情3 ShaderForge的简单使用
- Android butterknife简单使用篇
- JNI
- 内讧!迅雷大数据公司股权被内部人於菲窃取,并报案!
- ES6 你可能不知道的事
- Zookeeper(单机版)搭建
- wav文件格式分析详解
- CodeIgniter源码阅读笔记(1)——框架入口index.php
- 18.Python
- 深入理解数组的运算
- 一场没有硝烟的战争---端口争夺战