您的位置:首页 > 移动开发 > Android开发

Android Studio下使用JNI编程备忘录

2016-04-05 17:42 561 查看
1、下载安装NDK的过程略过,网上资料很多。

JNI官网规范见 http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/jniTOC.html
2、修改local.properties

如图,增加ndk路径。



3、修改app/build.gradle

代码如下,defaultConfig中增加ndk,模块名为java类名,abiFilters为底层架构。增加sourceSet。

import org.apache.tools.ant.taskdefs.condition.Os

apply plugin: 'com.android.application'

android {
compileSdkVersion 22
buildToolsVersion "21.1.2"

defaultConfig {
applicationId "cn.lxg.jniHello"
minSdkVersion 12
targetSdkVersion 22
versionCode 1
versionName "1.0"

ndk {
moduleName "MyNativeMethod"
stl "stlport_static"
ldLibs "log"
abiFilters "armeabi", "armeabi-v7a", "x86"
}
}
buildTypes {
debug {
// 显示Log
buildConfigField "boolean", "LOG_DEBUG", "true"
minifyEnabled false
shrinkResources true
}
}

sourceSets {
main {
jniLibs.srcDirs = ['libs']
}
}

}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}
4、新建java class,名字要与gradle中一致

定义了一个native的函数Display,在C中实现。

package cn.lxg.jniHello;

/**
* Created by 李晓光 on 2016/4/5.
*
*/
public class MyNativeMethod {
static {
System.loadLibrary("MyNativeMethod");
}
public native String DisplayHello();

}


5、新建native的.h文件和.cpp文件

h文件,注意文件名要严格按规范,与java类名一致。

#ifndef _Included_cn_lxg_jniHello_MyNativeMethod
#define _Included_cn_lxg_jniHello_MyNativeMethod
#ifdef __cplusplus
extern "C" {
#endif

#include <jni.h>
#include <android/log.h>

#ifndef LOG_TAG
#define LOG_TAG "MyNativeMethod"
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#endif

/*
* Class:
* Method:
* Signature:
*/
JNIEXPORT jstring JNICALL Java_cn_lxg_jniHello_MyNativeMethod_DisplayHello
(JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif
cpp文件,用了jni的函数生成一个jstring。

#include "cn_lxg_jniHello_MyNativeMethod.h"

JNIEXPORT jstring JNICALL Java_cn_lxg_jniHello_MyNativeMethod_DisplayHello
(JNIEnv *env, jobject){
LOGE("Hello! This is Lee!");

char cStr[] = "Hello! This is Lee!";
jstring str = env->NewStringUTF(cStr);
return str;
}


6、在Android程序中调用native函数

编译,运行,完成。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: