【问题标题】:Android ndk binder thread causing problems in appAndroid ndk binder线程导致应用程序出现问题
【发布时间】:2011-09-07 09:11:23
【问题描述】:

我有这个应用程序(只有一个活动),它使用一些 android UI 和一些本机 C++ 库来进行 OpenGL 绘图和计算。

似乎该活动自己创建了一些“绑定线程”,我很确定它会在我的本机调用中造成一些损坏。

什么是活页夹线程? 它们可以被删除或合并为一个吗?

【问题讨论】:

    标签: android android-layout android-widget android-ndk android-manifest


    【解决方案1】:

    终于找到了一些关于这个主题的好信息。

    • Binder 线程无法删除或合并,但您可以使用 HandlerRunnable 对象轻松地将函数调用重定向到主线程。

      Handler handle = new Handler(); //Will be associated with current thread
      handle.post(new Runnable ()
      {
          @Override public void run()
          {
          // Your code to be executed in this thread
          //  you can call native code here to make sure they run under this thread.
          }
      });
      
    • 但是,您不能在本机代码中使用它。因此,您的某些本机代码可能会产生意外错误。为此,您可以在 JNI 中同步您的代码,以尽量减少奇怪的行为。 (details)

      env->MonitorEnter(obj);
      // Your code 
      env->MonitorExit(obj);
      
    • 您还可以重定向代码的某些部分以在 UI 线程内执行(如果您希望在 UI 上获得性能,我不建议这样做)

      myActivity.runOnUiThread(new Runnable ()
      {
          @Override public void run()
          {
          // Your code 
          }
      });
      
    • 如果你像我一样使用GLSurfaceView,你也可以将代码重定向到GL线程中

      myGLSurfaceView.queueEvent(new Runnable()
      {
          @Override public void run() 
          {
              /* do something on the GLSurfaceView thread */
      }});
      

    请务必注意,android 将始终为 UI 创建一个单独的线程,因此从您的 UI 代码和其他地方调用本机代码显然会导致意外行为。

    此外,使用GLSurfaceView 将同样生成自己的渲染线程,因此要避免与本机代码发生相同类型的交互。但是,有了这些提示,您应该能够同步这些线程并使其完美运行;)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多