这次主要学习NDK C调用JAVA 类,这种做法可以作为回调,比如JNI层获取网络数据 然后回调JAVA层 把获取的网络数据传给应用层并显示。
创建一个简单的User类,和 SimpleAction.
在JNI层实例化一个User类,并设置值,传给SimpleAction类,然后JNI层调用doLogin方法 打印出User类的信息。
public class User {
public String uid;
public String username;
public int age;
public User() {
}
public void setUid(String uid) {
this.uid = uid;
}
public void setUsername(String username) {
this.username = username;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "uid:" + uid + ",username:" + username + ",age:" + age;
}
}
public class SimpleAction {
private User user;
public SimpleAction() {
}
public void doLogin(){
System.err.println("doLogin:" + this.user);
}
public void setUser(User u){
this.user = u;
}
}
编译工程后,获取相关签名
编写一个native方法。
public class JNI {
public native void processAction(SimpleAction action);
}
javah命令生成头文件
重点实现里面的函数体。
JNIEXPORT void JNICALL Java_com_birds_android_ndk_JNI_processAction
(JNIEnv *env, jobject job, jobject actionObj) {
jclass userCls = (*env)->FindClass(env,"com/birds/android/ndk/User");
if (userCls) {
// 找到User类的 MethodId.
jmethodID mid = (*env)->GetMethodID(env,userCls,"<init>","()V");
jobject userObj = (*env)->NewObject(env,userCls,mid);
// 得到User中Set方法的Method Id
jmethodID age = (*env)->GetMethodID(env, userCls, "setAge", "(I)V");
jmethodID username = (*env)->GetMethodID(env, userCls, "setUsername", "(Ljava/lang/String;)V");
jmethodID uid = (*env)->GetMethodID(env, userCls, "setUid", "(Ljava/lang/String;)V");
// 创建2个值给uid和username的.
jstring uidv = (*env)->NewStringUTF(env,"200212");
jstring unamev = (*env)->NewStringUTF(env,"birds");
jint agev = 34;
//设置值调用方法
(*env)->CallVoidMethod(env, userObj, age, agev);
(*env)->CallVoidMethod(env, userObj, username, unamev);
(*env)->CallVoidMethod(env, userObj, uid, uidv);
//把User实例传给SimpleAction
jclass actionCls = (*env)->GetObjectClass(env,actionObj);
jmethodID mid2 = (*env)->GetMethodID(env, actionCls, "setUser", "(Lcom/birds/android/ndk/User;)V");
(*env)->CallVoidMethod(env, actionObj, mid2, userObj);
//最后调用doLogin方法
jmethodID mid3 = (*env)->GetMethodID(env, actionCls, "doLogin", "()V");
(*env)->CallVoidMethod(env, actionObj, mid3);
}
}
在Activity里面直接调用即OK
SimpleAction action = new SimpleAction();
new JNI().processAction(action);