Monday, 18 January 2010

Android - NPAPI plugin - how to make a callback from the main thread

If you happen to be writing a browser plug-in using NPAPI/JNI for Android's built-in browser, and are doing some processing in the native side in C/C++ in a separate Posix thread; and want to get a callback into your native code from the main browser thread; you want to use this NPAPI function...!

void NPN_PluginThreadAsyncCall(NPP instance,
void (*func)(void *),
void *userData);

You can find some documentation on this if you search your Android source code for the file called npapi.cpp.

Basically, you call the above function from your native thread to register a callback function; the call to NPN_PluginThreadAsyncCall returns immediately. At some future point in the very near future, the browser will call your supplied function from the main browser thread, supplying the userData that you provided when you registered your callback.

Incidentally, if your Plug-in method is passed a JavaScript object that you're going to need to do something with at a later point (e.g. if you want to issue a deferred callback, through use of NPN_PluginThreadAsyncCall), you need to remember to keep your JavaScript object alive until you're ready to use it, by calling:

NPObject *NPN_RetainObject(NPObject *npobj);

Once you've used the object, remember to release it with:

void NPN_ReleaseObject(NPObject *npobj);

Hopefully that'll be of use to some people!

1 comment:

Eric G said...

Hi Pete,

Would you mind sharing with us how you managed to make a NPAPI plugin for the Android browser. I'm trying to do the same on my side but I'm struggling to make sense of the various conflicting information that can be found online. I managed to build a plugin based on the development/samples/BrowserSamplePlugin/* eclair source but it doesn't seem to load in the various device emulators from the SDK.