Welcome to Singapore blogs

Further notes on loading an external JAR / APK in Delphi on Android

Chee Wee's discoveries and tech blog

Changing the world one line of code at a time...
Generic Content

Further notes on loading an external JAR / APK in Delphi on Android

  • Comments 2

In my previous post, I showed how it's possible to load an external JAR / APK on Android, in Java. In Delphi, even if you're able to convert a JAR into an APK, there is no easy way to load the APK into your Delphi/Android application, until the Android2DelphiImport tool.

With the release of the Android2DelphiImport tool, you can now load an external class from a JAR / APK on Android within Delphi itself.

Here's the example that was shipped in the latest Android2DelphiImport release.

procedure TfrmLoadJarSample.Button1Click(Sender: TObject);
  LPath: string;
  LFullPath1, LFullPath2: string;
  LTestClass: JTestClass;
  D: Double;
  JavaClassHelper2: JJavaClassHelper2;
  JHelloWorld: JString;
  LPath := GetSharedFilesDir;

  ShowMessage(Format('copy APK files to %s directory before clicking Ok', [LPath]));
  // Copy ClassHelpers.apk and ClassHelpers2.apk manually to the directory shown above
  // before clicking Ok
  // Or you can copy using your own code

  LFullPath1 := IncludeTrailingPathDelimiter(LPath) + 'ClassHelpers.apk';
  LoadAPK(LFullPath1); // the magic function!!!

    LTestClass := TJTestClass.JavaClass.init(StringToJString('Hello world'));
    if Assigned(LTestClass) then
        D := LTestClass.getdouble; // returns 1.0
        ShowMessage(Format('Value is: %2.2f', [ D ]));
    ShowMessage('TJTestClass cannot be found!');

  LFullPath2 := IncludeTrailingPathDelimiter(LPath) + 'ClassHelpers2.apk';
  LoadAPK(LFullPath2); // the magic function!!! 
    JavaClassHelper2 := TJJavaClassHelper2.JavaClass.init;
    if Assigned(JavaClassHelper2) then
        JHelloWorld := JavaClassHelper2.getHelloWorld; // returns HelloWorld
    ShowMessage('TJJavaClassHelper2 cannot be found!');

As can be inferred from the above, ClassHelpers.apk and ClassHelpers2.apk are external APKs that are located on the SD card. Once you've given Android2DelphiImport a path to a JAR that is Android compatible, it produces the Delphi interface and after that, converts the JAR into an APK that you can use immediately, once you've uploaded it to your Android device.

The LoadAPK function is the magic function (shipped in the Android2DelphiImport tool) that made it all work easily and seamlessly.

The constructor to the imported class is inside the try except clause because it is possible for it to fail if Dalvik/ART is unable to load it.

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Post
Page 1 of 1 (2 items)
Blog - Monthly Archive List