JNI 和取消 AsyncTask

发布于 2024-12-13 09:14:31 字数 224 浏览 0 评论 0原文

我有一个 AsyncTask,在 doInBackground() 内部调用 C 函数,该函数会执行一段时间。当我通过调用 cancel(true) 取消我的 AsyncTask 时,它返回 true - 就像任务已终止一样,但是我仍然在“终止”后看到来自 C 代码的日志语句。

对我来说,C 函数似乎并没有真正终止。

我的问题是 - 如何正确终止 C 函数的执行?

I have an AsyncTask, and inside doInBackground() I call C function, which executes for some time. When I cancel my AsyncTask by calling cancel(true), it returns true - like task was terminated, however I still see log statements from C code after "termination".

For me it seems that C function is not really terminated.

My question is - how to terminate executing of C function correctly?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

吻安 2024-12-20 09:14:31

此处找到了答案。

这是C版本:

jclass thread = (*env)->FindClass(env, "java/lang/Thread");
jmethodID mCurThread = (*env)->GetStaticMethodID(env, thread, "currentThread", "()Ljava/lang/Thread;");
jmethodID mIsInterrupted = (*env)->GetMethodID(env, thread, "isInterrupted", "()Z");
jobject curThread = (jobject)(*env)->CallStaticObjectMethod(env, thread, mCurThread);

for (;;) {
    // do some stuff
    jboolean res = (jboolean)(*env)->CallBooleanMethod(env, curThread, mIsInterrupted);
    if (res == JNI_TRUE) {
        LOGI("INTERRUPTED");
    } else {
        LOGI("WORKING");
    }
}

Found answer here.

Here is C version:

jclass thread = (*env)->FindClass(env, "java/lang/Thread");
jmethodID mCurThread = (*env)->GetStaticMethodID(env, thread, "currentThread", "()Ljava/lang/Thread;");
jmethodID mIsInterrupted = (*env)->GetMethodID(env, thread, "isInterrupted", "()Z");
jobject curThread = (jobject)(*env)->CallStaticObjectMethod(env, thread, mCurThread);

for (;;) {
    // do some stuff
    jboolean res = (jboolean)(*env)->CallBooleanMethod(env, curThread, mIsInterrupted);
    if (res == JNI_TRUE) {
        LOGI("INTERRUPTED");
    } else {
        LOGI("WORKING");
    }
}
眼角的笑意。 2024-12-20 09:14:31

当 AsyncTask 终止时,运行 C 函数的线程将被中断。您需要注意长时间运行的 C 代码中的中断状态(检查 isInterrupted?)并手动退出。

编辑:

查看xuggle(ffmpeg JNI包装器),特别是csrc/com/xuggle/ferry/JNIHelper.cpp 以获得完整且良好实现的解决方案。

When the AsyncTask is terminated the thread that is running your C function is interrupted. You need to pay attention to the interrupt state in your long-running C code (check isInterrupted?) and exit manually.

Edit:

Check out xuggle (ffmpeg JNI wrapper), especially csrc/com/xuggle/ferry/JNIHelper.cpp for a complete and nicely implemented solution.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文