//回调,包括子线程回调
JNIInvokeMethod jniInvokeMethod = new JNIInvokeMethod();
jniInvokeMethod.nativeCallback(new ICallbackMethod() {
@Override
public void callback() {
Log.d(TAG, "callback: " + Thread.currentThread().getName());
}
});
jniInvokeMethod.nativeThreadCallback(new IThreadCallback() {
@Override
public void callback() {
Log.d(TAG, "callback: " + Thread.currentThread().getName());
}
});
public interface ICallbackMethod {
void callback();
}
public interface IThreadCallback {
void callback();
}
public class JNIInvokeMethod extends BaseOperation {
@Override
public void invoke() {
}
public native void nativeCallback(ICallbackMethod mICallbackMethod );
public native void nativeThreadCallback(IThreadCallback mIThreadCallback);
}
static jclass threadClazz;
static jmethodID threadMethod;
static jobject threadObject;
extern "C"
JNIEXPORT void JNICALL
Java_com_jdqm_ndktutorials_jni_JNIInvokeMethod_nativeCallback(JNIEnv *env, jobject instance,
jobject callback) {
LOGD("nativeCallback");
jclass callbackClazz = env->GetObjectClass(callback);
jmethodID callbackMethod = env->GetMethodID(callbackClazz, "callback", "()V");
env->CallVoidMethod(callback, callbackMethod);
}
void *threadCallback(void *) {
//env 是不能跨线程
JavaVM *gVM = getJvm();
JNIEnv *env = nullptr;
if (gVM->AttachCurrentThread(&env, nullptr) == 0) {
env->CallVoidMethod(threadObject, threadMethod);
gVM->DetachCurrentThread();
}
return JNI_OK;
}
extern "C"
JNIEXPORT void JNICALL
Java_com_jdqm_ndktutorials_jni_JNIInvokeMethod_nativeThreadCallback(JNIEnv *env,
jobject instance,
jobject callback) {
//env 是不能跨线程的
threadClazz = env->GetObjectClass(callback);
threadMethod = env->GetMethodID(threadClazz, "callback", "()V");
threadObject = env->NewGlobalRef(callback);
pthread_t handle;
pthread_create(&handle, nullptr, threadCallback, nullptr);
}