if(event == nullptr || sender == nullptr) {
return;
}
EventData eventData;
eventData.eventPointer = event;
eventData.sender = sender;
eventMap.insert(std::pair
}
void eeSleepWakeCallback(int result, void* sender) {
JniTester *tester = (JniTester *) sender;
tester->onResultCallback(result);
}
JniTester::JniTester() {
EventManager::getI
nstance().addEvent(eeSleepWake, (void*)eeSleepWakeCallback, this);
}
··· void JniTester::getThreadResult() { ThreadTest *test = new ThreadTest(); test->sleepThread(); } ··· 耗时函数的具体实现:
void ThreadTest::sleepThread() {
std::thread cal_task(&ThreadTest::makeSleep, this);
cal_task.detach();
}
void ThreadTest::makeSleep() {
sleep(2);
}
这一步我们是通过新建一个线程,并让其等待2S来模拟异步耗时操作
4. 异步回调的实现
=========================================================================
private OnResultCallback callback;
public void setOnResultCallback(OnResultCallback callback) {
this.callback = callback;
}
public interface OnResultCallback {
void onResult(int result);
}
public void onResult(int result) {
if (this.callback != null) {
callback.onResult(result);
}
}
通过向单例的事件持有类获取对应的事件枚举,获取到其对应的函数指针,并调用该函数指针实现:
void ThreadTest::makeSleep() {
sleep(2);
EventData eventData = EventManager::singleton().getEventData(eeSleepWake);
onSleepWake wake = (onSleepWake)eventData.eventPointer;
if(wake) {
wake(12345, eventData.sender);
}
}
因为我们在第三章节第7步注册的函数指针是eeSleepWakeCallback, 因此,这里会调用到这个函数:
void eeSleepWakeCallback(int result, void* sender) {
JniTester *tester = (JniTester *) sender;
tester->onResultCallback(result);
}
通过sender确定具体的对象,调用其onResultCallback函数
void JniTester::onResultCallback(int result) {
JNIEnv *env = NULL;
int status = f_jvm->GetEnv((void **) &env, JNI_VERSION_1_4);
bool isInThread = false;
if (status < 0) {
isInThread = true;
f_jvm->AttachCurrentThread(&env, NULL);
}
if (f_cls != NULL) {
jmethodID id = env->GetMethodID(f_cls, “onResult”, “(I)V”);
if (id != NULL) {
env->CallVoidMethod(f_obj, id, result);
}
}
if (isInThread) {
f_jvm->DetachCurrentThread();
}
}
这里因为缺少java环境,因此我们需要将该线程挂载到jvm上执行,并获取对应的JNIEnv ,通过jnienv获取java层的回调触发方法onResult并执行。
5.效果
==================================================================
编写测试代码:
JniTester tester = new JniTester();
Log.d(“zyl”, "startTime = " + System.currentTimeMillis());
tester.setOnResultCallback(result -> {
Log.d(“zyl”, "endTime = " + System.currentTimeMillis());
Log.d(“zyl”, "result = " + result);
});
tester.requestData();
编写测试代码:
JniTester tester = new JniTester();
Log.d(“zyl”, "startTime = " + System.currentTimeMillis());
tester.setOnResultCallback(result -> {
Log.d(“zyl”, "endTime = " + System.currentTimeMillis());
Log.d(“zyl”, "result = " + result);
});
tester.requestData();