Android JNI Bridge and Custom Classes.dex


By creating a custom Classes.dex you can get access to 3rd party Java JAR APIs from your application. For my Integrate More Android with a JNI Call to your Android App Developer Skill Sprint I created a demo app that demonstrates creating a custom Classes.dex. This is a new feature in XE6 and Appmethod 1.14. [Download the demo] [Download the slides] The Demo app uses the Base64Coder JAR file (included). To build the demo:

Examine the createdex.bat file to make sure it refers to the correct location for your dx.bat utility and the fmx.jar & android-support-v4.jar files.
Run the createdex.bat file to create the classes.dex file which includes the two jar files above, plus the base64coder.jar file.
Double check that the Deployment Manager references the new classes.dex and not the old ones, and that the remote path is “classes\”
Notice that the android.JNI.Base64Coder.pas file wraps and exposes the methods of the base64coder class.
Run the app on your Android device and verify that it works as expected.

The Base64Coder.JAR is Android specific, so it will not work on iOS or Windows. Some additional notes from the Developer Skill Sprint: Some useful units for making JNI calls

Androidapi.Jni – Java Native Interface type definitions
Androidapi.JNIBridge – The JNI Bridge
Androidapi.JNI.JavaTypes – JString and other common types.
Androidapi.Helpers – JStringToString and other useful conversions.
FMX.Platform.Android– Useful platform methods like GetAndroidApp, MainActivity and ConvertPointToPixel
Others useful units: Androidapi.AppGlue, Androidapi.JNIMarshal, Androidapi.JNI.Embarcadero
For more see: C:\Program Files (x86)\Embarcadero\Studio\14.0\source\rtl\android (Object Pascal) and C:\Program Files (x86)\Embarcadero\Studio\14.0\include\android\rtl (C++)

You will want to make use of Conditional Defines in Object Pascal and Predefined Macros in C++. In my blog post on Android Settings I showed how to make a JNI call with Object Pascal, but you can also look at the DeviceInfo Mobile Code Snippet in both C++ and Object Pascal. To create your own JNI Bridge wrappers, look at the source code in C:\Program Files (x86)\Embarcadero\Studio\14.0\source\rtl\android (Object Pascal) and C:\Program Files (x86)\Embarcadero\Studio\14.0\include\android\rtl (C++). You can also consider the following 3rd party utilities:

Java2Pas by Software Union
JavaImport by WinSoft
Android2DelphiImport by CHUA Chee Wee aka “Chewy” (also an Embarcadero MVP) [my previous review]

If you just want to include standard Android APIs then check out the FMXExpress (also an Embarcadero MVP) project on GitHub that includes all the Android APIs. Here is the video replay of my skill sprint

Also, check out Brian Long’s video on accessing the Android API with XE5

Comments are closed.