How to Make Your PDF Viewer Handle PDF Files with Intent Filters in Android

Introduction

In this article, we will learn how to make your PDF viewer handle PDF files with intent filters in Android.

Here, we create an app that can open a PDF file. When you click on a pdf file, it displays a list of applications that can handle pdf files; therefore, after you install your app, it will appear in the list if a user clicks on your app's logo and views a pdf file displayed in your app. This functionality is supported due to the VIEW intent filter.

We will also include a SEND intent filter in this app, allowing it to appear on a list whenever a PDF file is shared. Therefore, when someone taps on the logo of your app, a pdf file opens in it.

Create a PDF Viewer App that handles VIEW And SEND Intent Filter

Step 1

Create a new project in the Android Studio and select an empty activity.

Create A Project

Step 2

Give the project a name, select the save location folder, and click the finish button.

Give project name and select project path

Step 3

Add the following dependency in the build.gradle app level file.

implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'

And if jcenter is unavailable in your settings.gradle file, add jcenter(). After that, your settings.gradle file looks like the following. it is based on which Android Studio you used; sometimes, we add jcenter() in build.gradle Project level file.

settings.gradle

pluginManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        jcenter()
    }
}
rootProject.name = "PDFViewer"
include ':app'

Step 4

Create the activity_main.xml file as shown below.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <!-- PDFView widget -->
    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfViewer"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 5

Declare PDFView objects and declare the variable EXT_STORAGE_PERMISSION_CODE to take permission from the user for READ_EXTERNAL_STORAGE in the MainActivity.java class.

private final int EXT_STORAGE_PERMISSION_CODE = 1;
private PDFView pdfView;

Step 6

Now take the READ_EXTERNAL_STORAGE permission from the user in the onCreate() method in MainActivity.java class.

 if (ContextCompat.checkSelfPermission(
     MainActivity.this,
     android.Manifest.permission.READ_EXTERNAL_STORAGE) ==
   PackageManager.PERMISSION_DENIED) {
   ActivityCompat.requestPermissions(
     MainActivity.this,
     new String[] {
       android.Manifest.permission.READ_EXTERNAL_STORAGE
     },
     EXT_STORAGE_PERMISSION_CODE);
   Log.d("PERMISSION", "After getting permission: " + android.Manifest.permission.READ_EXTERNAL_STORAGE + " " + ContextCompat.checkSelfPermission(
     MainActivity.this,
     android.Manifest.permission.READ_EXTERNAL_STORAGE));

 } else {
   // We were granted permission already before
   Log.d("PERMISSION", "Already has permission to write to external storage");
 }

Step 7

Include the READ_EXTERNAL_STORAGE permission in the manifest file.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Step 8

Get the intent and know whether it is a send or a view intent before accessing the URI. And set the URI to our pdfviewer object in the MainActivity.java class's onCreate() method.

Intent intent = getIntent();
Uri uri;

pdfView = findViewById(R.id.pdfViewer);

if (Intent.ACTION_VIEW.equals(intent.getAction())) {
    uri = intent.getData();
    pdfView.fromUri(uri).load();
}

if (Intent.ACTION_SEND.equals(intent.getAction())) {
   uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
   pdfView.fromUri(uri).load();
}

Final MainActivity.Java File

package com.example.pdfviewer;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

import com.github.barteksc.pdfviewer.PDFView;

public class MainActivity extends AppCompatActivity {
    private final int EXT_STORAGE_PERMISSION_CODE = 1;
    private PDFView pdfView;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ContextCompat.checkSelfPermission(
                MainActivity.this,
                android.Manifest.permission.READ_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(
                    MainActivity.this,
                    new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
                    EXT_STORAGE_PERMISSION_CODE);
            Log.d("PERMISSION", "After getting permission: "+ android.Manifest.permission.READ_EXTERNAL_STORAGE + " " + ContextCompat.checkSelfPermission(
                    MainActivity.this,
                    android.Manifest.permission.READ_EXTERNAL_STORAGE));

        } else {
            // We were granted permission already before
            Log.d("PERMISSION", "Already has permission to write to external storage");
        }


        Intent intent = getIntent();
        Uri uri;

        pdfView = findViewById(R.id.pdfViewer);

        if (Intent.ACTION_VIEW.equals(intent.getAction())) {
            uri = intent.getData();
            pdfView.fromUri(uri).load();
        }

        if (Intent.ACTION_SEND.equals(intent.getAction())) {
            uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
            pdfView.fromUri(uri).load();
        }

    }
}

Step 9

In the manifest file in your activity, define the intent view and send as follows.

 <activity
       android:name=".MainActivity"
       android:exported="true">
       <intent-filter>
           <action android:name="android.intent.action.MAIN" />
           <category android:name="android.intent.category.LAUNCHER" />
       </intent-filter>
       <intent-filter>
           <action android:name="android.intent.action.VIEW" />
           <category android:name="android.intent.category.DEFAULT" />
           <category android:name="android.intent.category.OPENABLE" />
           <data android:scheme="file" />
           <data android:scheme="content" />
           <data android:mimeType="application/pdf" />
           <data android:pathPattern=".*\\.pdf" />
           <data android:host="*" />
       </intent-filter>
       <intent-filter>
           <action android:name="android.intent.action.SEND" />
           <category android:name="android.intent.category.DEFAULT" />
           <data android:mimeType="application/pdf" />
       </intent-filter>
</activity>

The first intent in the list above is for Launcher activity, the second is for View Or Open, and the third is for Send Or Share. 

Step 10

Run your app now, and when it asks for permission, provide it. After that, exit the app and try to open any PDF file from the file manager. You will see a list of different apps that can open PDF files; your file should now appear on that list and in share options as well.

OUTPUT 1

OUTPUT 2

OUTPUT 3

Summary

So you see, creating a PDF Viewer In Android with little coding is very easy.

In this article, we will learn How to Make Your PDF Viewer Handle PDF Files with Intent Filters in Android.

If you like my article, please like this article and comment your views on it.

Thank you. Enjoy Coding.


Similar Articles