Android / Java: How to call object methods created in another thread?

In my Android NDK application, the C ++ library runs in a different thread than the ui thread. A JNI call from C ++ creates an instance of the Java Foo class. I would like to have another Java object panel created in the user interface thread to call methods on Foo. How should I do it?

Difficulty bonus: Foo has several proprietary methods that call the corresponding JNI functions from the C ++ library. How to ensure that these calls are thread safe?

Bonus for difficulty 2: Some of the Bar methods actually override the callback methods, in particular WebViewClient. The return code of some methods depends on the result of calling the Foo method. So the call to Foo was supposed to happen immediately.

+3
source share
4 answers

Try the Handler class. Build a handler in the Foo constructor. Pass the reference to the Bar class in some way. Call Bar Handler.post ().

To do this, the thread must have a message queue. If this is a purely worker thread, then calling methods directly is not the answer; there is no AFAIR thread interrupt mechanism. To transfer material to a workflow, you need to simulate a message queue for a while - have a Runnnable object queue (to which Bar is added) and check it from time to time.

Ensuring thread safety is a separate big issue. SO is not large enough for everything that has been said and done on this topic.

0
source

, 1 2, 2 , 1 , 2.

2, java Java, , ?

, java :

    // object of this type instantiated on thread 2 and called from thread 1
public class thread2Class  {
    public void doSomething(...) {
        synchronized (this) {
           // call java or jni mthod
        }
    }
 }
0

, . 1 Thread 2. Thread 2 Thread 1. Thread 1 , . 1 - UI, Thread 2 - . 2 - / . , . Thread 1 , , , .

0

I would probably try using something like beginInvoke()to queue messages in a thread appropriately. It has been noted here that it beginInvoke()can be ridiculed using Activity.runOnUiThread(), or correctly used AsyncTask().

0
source

Source: https://habr.com/ru/post/1788577/


All Articles