JNI安装环境到编写笔记

来源:互联网 发布:淘宝卖视频 违规 编辑:程序博客网 时间:2024/05/22 03:26
  1)搭建NDK开发环境

       首先需要了解的是jni就是基于NDK开发环境的,所以我们编写jni代码就必须要有一个NDK的环境才能成功编译。

       NDK下载目录:https://developer.android.com/ndk/index.html

       打开Eclipse,点Window->Preferences->Android->NDK,设置NDK路径例如我的路径【/home/szxb/eclipse/android-ndk-r12b】。

       2)新建一个Android工程,在工程上右键点击AndroidTools->Add Native Support.然后给自己的.so文件取个名字,例如:szxb。

       3)这时候工程就会多一个jni的文件夹,jni下有Android.mk和szxb.cpp文件。Android.mk是NDK工程的Makefile,szxb.cpp就是NDK的源文件。

       4)还有一个文件需要了解Application.mk可自行添加,代表你的应用程序需要哪个模块;如APP_ABI := armeabi。

      5)现在开始编写jni部分

test.cpp(1)

static const char* g_pJNIREG_CLASS = "com/test/testjni"; //这路径属于jvm层也就是java上层代码调用这里的函数jint native_testOpen(JNIEnv* env, jclass obj,int baud){……}static JNINativeMethod g_Methods[] ={{"testOpen","(I)I",     (void*)native_testOpen},//(I)I参数:第一个I代表函数类型,第二个I代表参数类型};const char* test_get_class_name(){return g_pJNIREG_CLASS;}JNINativeMethod* test_get_methods(int* pCount){*pCount = sizeof(g_Methods) /sizeof(g_Methods[0]);return g_Methods;}


test.h(2)

#ifndef TEST_H_#define TEST_H_const char* test_get_class_name();JNINativeMethod* test_get_methods(int* pCount);#endif

test_register.cpp(3)

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <assert.h>#include <jni.h>#include "test.h"static int register_native_methods(JNIEnv* env, const char* strClassName, JNINativeMethod* pMethods, int nMethodNumber){jclass clazz;clazz = env->FindClass(strClassName);if(clazz == NULL)return JNI_FALSE;if(env->RegisterNatives(clazz, pMethods, nMethodNumber) < 0)return JNI_FALSE;return JNI_TRUE;}/* * Register native methods for all class * */static int register_native_for_all_class(JNIEnv* env){int nCount = 0;JNINativeMethod* pMethods = test_get_methods(&nCount);return register_native_methods(env,test_get_class_name(),pMethods, nCount);}JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved){JNIEnv* env = NULL;jint nResult = -1;if(vm->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK){return -1;}assert(env != NULL);if(!register_native_for_all_class(env))return -1;return JNI_VERSION_1_4;}

在目录src/com/test/下面有一个testjni.java(4)

package com.example.jni;public class libtest {static {try {System.loadLibrary("test"); //你的库名} catch (Throwable e) {Log.e("jni", "i can't find business so!");e.printStackTrace();}}public native static int testOpen(int baud); //接口函数(提供上层的API) 

6)右键工程点击Properties->C/C++ Build里面的Builder Settings中Build command目录修改成你的ndk-build;然后开始编译你的jni生成so库。




原创粉丝点击