首页 > 解决方案 > 为什么调用 JNI 回调时我的 Android 测试会崩溃?

问题描述

我正在打包一个 C++ 库以在我的 Android 项目中使用。该库有几个异步函数,需要在 JNI 层上进行一些工作。基本上,我期待IThreadRunner在 C++ 端创建我的 lib 需要的任何后台线程。我有一个 JNI 的子类,它将附加和分离创建的线程,以便允许回调。在普通的 Android 应用程序中,一切都像魅力一样发挥作用。但是,当从 androidTest 调用异步代码时,我在JNI 的 java 回调中收到 JNI 错误(崩溃) 。

2019-08-22 09:10:44.785 11897-11897/---.-----.------ A/art: art/runtime/java_vm_ext.cc:470] JNI DETECTED ERROR IN APPLICATION: thread Thread[1,tid=11897,Native,Thread*=0xabd8b400,peer=0x754d6000,"main"] using JNIEnv* from thread Thread[1,tid=11897,Native,Thread*=0xabd8b400,peer=0x754d6000,"main"]

当我没有将回调线程附加到 JNI 之前,我已经经历过这些错误。现在情况并非如此。如果您在此错误消息中进行了仔细检查,它表示线程 X 正在尝试使用线程 X 中的 JNIEnv*,这是完全可以接受的,不应该是错误的。

请注意,这只发生在运行检测测试 (androidTest) 时。我知道测试在它自己的线程中运行,但我使用runBlocking(Dispatchers.Main) {的行为与我在普通 Android 应用程序中看到的行为相同。

这是我的测试文件正文的一部分

package ---.-----.------

import android.support.test.runner.AndroidJUnit4
import android.util.Log
import ---.-----.------.-----------
import ---.-----.------.------
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith

/**
 * Instrumented test, which will execute on an Android device.
 *
 * See [testing documentation](http://d.android.com/tools/testing).
 */
@RunWith(AndroidJUnit4::class)
class MyInstrumentedTest {
    @Test
    fun basicSocketTest() = runBlocking {
         ...
    }
}

标签: androidmultithreadingjunitjava-native-interface

解决方案


推荐阅读