Using the Android JNI bridge to open a PDF

Written by Sarina D on Posted in Tips, Tricks & Techniques

Unlike iOS, the Android browser does not have built-in PDF support. If you click a link for a PDF, it will download the file and you can open it in a separate application, but it will not render it in the browser.
You can use intents on Android to present the user with an option to open the file using a pdf reader app on their Android device. Jim McKeeth has created some great tutorials and webinars on using the JNI bridge.

Here is a code snippet that shows you how to open a remote PDF using the installed pdf reader apps on your Android device by making a JNI call.

Object Pascal:

  • Create a new Multi-Device Application
  • Place a TButton onto your Form
  • Change the Button Text to 'Open PDF'
  • Add the following units to your uses clause and set up a button on-click event:
uses
Androidapi.Helpers, FMX.Helpers.Android,
Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNI.Net,
Androidapi.JNI.JavaTypes;

procedure TForm7.Button2Click(Sender: TObject);
var
  MyIntent: JIntent;
  URL: string;
begin
  MyIntent := TJIntent.JavaClass.init(TJIntent.JavaClass.ACTION_VIEW,
  TJnet_Uri.JavaClass.parse(StringToJString('http://www.MYURL.com/MY.pdf')));
  SharedActivity.startActivity(MyIntent);
end;
end

C++:

  • Create a new Multi-Device Application
  • Place a TButton onto your Form
  • Change the Button Text to 'Open PDF'
  • Add the following header files to your Unit1.h file
    #include <Androidapi.Helpers.hpp>    // added
    #include <FMX.Helpers.Android.hpp>   // added
    #include <Androidapi.JNI.GraphicsContentViewText.hpp>       // added
    #include <Androidapi.JNI.Net.hpp>                 // added
    #include <Androidapi.JNI.JavaTypes.hpp>     // added
  • Setup the following on-click event:
void __fastcall TForm6::Button1Click(TObject *Sender)
{
   _di_JIntent MyIntent;
   String URL;

   {
	   MyIntent = TJIntent::JavaClass->init(TJIntent::JavaClass->ACTION_VIEW,
	   TJnet_Uri::JavaClass->parse(StringToJString("http://www.MYURL.com/MY.pdf")));
	   SharedActivity()->startActivity(MyIntent);
   }
}

Tags: Android C++ CPP JNI JNI Bridge



About
Gold User, Rank: 5, Points: 558

Check out more tips and tricks in this development video: