Android Studio下使用JNI编程备忘录

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函数

编译,运行,完成。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值