2

I have this app (Only one activity) that use some android UI and some native C++ lib to do OpenGl drawing and calculation.

It seems like the activity creates some "binder thread" on it's own, and I'm pretty sure it causes some corruption amongs my native calls.

What are the binder threads ? Can they be removed or merge into one ?

oberthelot
  • 1,310
  • 1
  • 11
  • 23

1 Answers1

4

Finally found some good infos on the subject.

  • Binder threads can't be removed or merge, but you can redirect function calls into the main thread pretty easily by using Handler and Runnable objects.

    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.
        }
    });
    
  • But, you can't use that inside your Native code. So it's possible that some of your native code create unexpected fault. For that you can synchronize your code inside JNI to minimize weird behavior. (details)

    env->MonitorEnter(obj);
    // Your code 
    env->MonitorExit(obj);
    
  • You can also, redirect some portion of your code to be executed inside the UI thread (which I don't recommend if you want performance on the UI)

    myActivity.runOnUiThread(new Runnable ()
    {
        @Override public void run()
        {
        // Your code 
        }
    });
    
  • If you use a GLSurfaceView like I do, you can also redirect code into the GL thread

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

It's important to notice that android will always create a separate thread for the UI, so calling native code from your UI code, and from somewhere else could obviously cause unexpected behavior.

Also, using GLSurfaceView will equally generate its own thread for rendering, so the same kind of interraction with native code is to avoid. But, with those few hints, you should be able to synchronize those threads and make it work flawlessly ;)

occulus
  • 16,959
  • 6
  • 53
  • 76
oberthelot
  • 1,310
  • 1
  • 11
  • 23
  • This has some useful advice too: http://blogs.arm.com/software-enablement/238-10-android-ndk-tips/ – occulus Dec 20 '11 at 19:23
  • And of course: http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html – occulus Dec 20 '11 at 19:26
  • Note that **Handler** is not limited to UI Thread. You can create a new **HandlerThread** anytime, and **post()** runnables to be executed on that thread. – Alex Cohn Nov 05 '18 at 09:02