UI freezing can happen if a blocking JNI API is called in a main thread. For this case, put the calling code into a child thread should work, but better refine the JNI to be non-blocking model: 1. In Java code, modify the API to be as 2 steps: one immediate native call, follows with waiting for notification; 2. In JNI code, create a sepearate native thread for your heavy function and directly return to Java; 3. In the created native thread code, notify Java once finishes execution; 4. Java gets the notification and wakes up a waiting object or to post a message; 5. This way Java can offer more API patterns, with async call, sync call or sync call with timeout threshold;
Native Code example: frameworks\base\core\jni\android_bluetooth_ScoSocket.cpp static jboolean connectNative(...) // maps to Java connectNative(); {... pthread_create(...,...,&work_thread,...) return JNI_TRUE; } static void *work_thread //child thread created by JNI function, able to call a native blocking call {... jvm->AttachCurrentThread(); ... // method_onConnected was initially mapped to env- >GetMethodID(clazz, "onConnected", "(I)V"); env->CallVoidMethod(data->nat->object, method_onConnected, sk); ... jvm->DetachCurrentThread(); } Java Code example: frameworks\base\core\java\android\bluetooth\ScoSocket.java {... private native boolean connectNative(); // THIS ONE will trigger a native blocking operation, but Java won't block; private synchronized void onConnected(); // THIS ONE will be directly trigger by native thread; ... } This way public connect(String address) will be a non-blocking API along with messages notifying BluetoothHandsfree.java On May 12, 4:38 am, fadden <fad...@android.com> wrote: > On May 10, 10:36 pm, Oceanedge <newsforhar...@gmail.com> wrote: > > > I need to implement a JNI which render image with 3-party native > > function. This function call is time consuming, it cost about 1s to > > return. I found during that time, even if I call the JNI within > > another Java thread, the whole Dalvik VM is blocked. UI is frozen. I > > guess that's because Dalvik doesn't implement Java thread with a > > native thread, so any time consuming native function call will block > > the whole VM. > > Your assumptions are incorrect -- threads in Dalvik are implemented > with Linux pthreads. > > Attach a debugger to your process, and when the UI appears to be > locked up, stop the app and examine the stack trace for the main > thread. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "android-framework" group. To post to this group, send email to android-framework@googlegroups.com To unsubscribe from this group, send email to android-framework+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/android-framework?hl=en -~----------~----~----~----~------~----~------~--~---