Android中Native的創(chuàng)建以及調(diào)用
1.創(chuàng)建需要的native方法:
public class Method {
public static String getUUid(){
return UUID.randomUUID().toString();
}
public native static void callStaticMethod();
public native static Point createPoint();
}
之后通過javac -h ./ Method.jav生成需要的頭文件(./ 表示當(dāng)前目錄)钦扭,內(nèi)容如下:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_yppcat_test_Method */
#ifndef _Included_com_yppcat_test_Method
#define _Included_com_yppcat_test_Method
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_yppcat_test_Method
* Method: callStaticMethod
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_yppcat_test_Method_callStaticMethod
(JNIEnv *, jclass);
#ifdef __cplusplus
}
#endif
#endif
將頭文件拷貝到cpp目錄下,新建對應(yīng)的.cpp文件并實(shí)現(xiàn)相應(yīng)的方法:
#include "Method.h"
#include <android/log.h>
#include <stdio.h>
extern "C" {
//先調(diào)用native方法,native中再調(diào)用java的方法
JNIEXPORT void JNICALL Java_com_yppcat_test_Method_callStaticMethod
(JNIEnv *env, jclass j_clz) {
jmethodID j_mid = env->GetStaticMethodID(j_clz, "getUUid", "()Ljava/lang/String;");
jstring j_uuid = static_cast<jstring>(env->CallStaticObjectMethod(j_clz, j_mid));
char *uuid = const_cast<char *>(env->GetStringUTFChars(j_uuid, NULL));
__android_log_print(ANDROID_LOG_ERROR, "allStaticMethod", "c_uuid = %s", uuid);
printf("c_uuid = %s", uuid);
}
JNIEXPORT jobject JNICALL Java_com_yppcat_test_Method_createPoint(JNIEnv *env, jclass) {
//調(diào)用native方法構(gòu)造Java對象并返回
jclass j_clz = env->FindClass("com/yppcat/test/Point");
jmethodID j_mid = env->GetMethodID(j_clz, "<init>", "(II)V");
jobject point = env->NewObject(j_clz, j_mid, 11, 22);
jmethodID j_setY = env->GetMethodID(j_clz, "setY", "(I)V");
env->CallVoidMethod(point, j_setY, 100);
return point;
}
}
Point代碼如下:
package com.yppcat.test;
public class Point {
public Point(int x, int y) {
this.x = x;
this.y = y;
}
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
另外如果用到其他的sdk相關(guān)的類,在生成頭文件是需要用到以下命令:
javac -h ./ -classpath <sdk全路徑> xxx.java