Use Intent to view PDF file

Description

The following code shows how to Use Intent to view PDF file.

Example

Main layout xml file


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="hello"
    />
</LinearLayout>

Main Activity Java code


package com.java2s.myapplication4.app;
/*from w  w  w . j  a  va2  s .  co  m*/
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;

import java.io.File;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Create a Uri for files on external storage
        File externalFile = new
                File(Environment.getExternalStorageDirectory(), "yourPDF.pdf");
        Uri external = Uri.fromFile(externalFile);
        viewPdf(external);

    }

    private void viewPdf(Uri file) {
        Intent intent;
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(file, "application/pdf");
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("No Application Found");
            builder.setMessage("We could not find an application on your device to view PDFs.  Would you like to download one from Android Market?");
            builder.setPositiveButton("Yes, Please",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent marketIntent = new Intent(Intent.ACTION_VIEW);
                            marketIntent.setData(Uri.parse("market://details?id=com.adobe.reader"));
                            startActivity(marketIntent);
                        }
                    });
            builder.setNegativeButton("No, Thanks", null);
            builder.create().show();
        }
    }
}
Use Intent to view PDF file




















Home »
  Android »
    Android Basics »




Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS