如何打开从Android应用PDF文件(在一个单独的PDF查看器应用程序)

如何打开从Android应用PDF文件(在一个单独的PDF查看器应用程序)

问题描述:

我们的目标是能够到一个PDF文件添加到应用程序的资产的文件夹,并让用户在PDF的应用程序(ezPDFReader,则Adobe Reader等​​)打开该PDF。这不完全是简单的PDF首先需要复制从资产文件夹到设备上存储。如果设备上没有PDF浏览器的应用程序,我们需要显示警告信息,并引导他们到Play商店下载一个。

The goal is to be able to add a PDF file to the "assets" folder of an app, and let the user open that PDF in a PDF app (ezPDFReader, Adobe Reader, etc). This is not entirely straightforward as the PDF first needs copying from the assets folder onto the device storage. If the device has no PDF viewer app on it, we need to show a warning message and direct them to the Play Store to download one.

下面是为我工作的解决方案。这是一个名为 PdfHandler 类,这里是你如何使用它 - 只是把PDF文件中的资产文件夹中。这将在PDF查看器应用程序打开它(如果可用),如果没有显示警告信息,并引导用户到Adobe阅读器播放存储的条目。

Here's the solution that worked for me. It's a class called PdfHandler and here's how you use it - just put the pdf file in the assets folder. It will open it in a PDF viewer app if one is available, and if not show a warning message and direct the user to the Adobe Reader Play Store entry.

PdfHandler pdf = new PdfHandler(this);
pdf.openPdf("document.pdf");

该PdfHandler类。你应该将文本资源投入到Android的字符串资源。

The PdfHandler class. You should move text resources into Android string resources.

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.net.Uri;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Handles the opening of PDF files, using whatever app the user has installed to view PDFs
 * If no PDF app installed, shows a warning and directs them to appropriate Store listing
 */
public class PdfHandler {

    public PdfHandler(Context context) {
        this.context = context;
    }

    public void openPdf(String filename) {
        if (isPdfAppAvailable()) {
            copyPdfAndOpenIt(filename);
        } else {
            showPdfWarning();
        }
    }

    private void copyPdfAndOpenIt(String filename) {
        try {
            File file = copyPdfFromAssetsToStorage(filename);
            startPdfIntent(file);
        } catch (Exception e) {
            Log.e("PdfHandler", "Error handling the PDF file", e);
        }
    }

    private File copyPdfFromAssetsToStorage(String filename) throws Exception {
        String tempFilename = "temp.pdf";
        AssetManager is = context.getAssets();
        InputStream inputStream = is.open(filename);
        String outFilename = context.getFilesDir() + "/" + tempFilename;
        FileOutputStream outputStream = context.openFileOutput(tempFilename, Context.MODE_WORLD_READABLE);
        copy(inputStream, outputStream);
        outputStream.flush();
        outputStream.close();
        inputStream.close();
        return new File(outFilename);
    }

    private void copy(InputStream fis, FileOutputStream fos) throws IOException {
        byte[] b = new byte[8];
        int i;
        while ((i = fis.read(b)) != -1) {
            fos.write(b, 0, i);
        }
    }

    private boolean isPdfAppAvailable() {
        PackageManager packageManager = context.getPackageManager();
        Intent testIntent = new Intent(Intent.ACTION_VIEW);
        testIntent.setType("application/pdf");
        List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    private void startPdfIntent(File file) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(file);
        intent.setDataAndType(uri, "application/pdf");
        context.startActivity(intent);
    }

    private void showPdfWarning() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage("Please install an app to view PDF file");
        builder.setCancelable(false);
        builder.setPositiveButton("Install", getButtonListener());
        builder.setNegativeButton("Cancel", null);
        builder.setTitle("PDF Viewer");
        AlertDialog alert = builder.create();
        alert.show();
    }

    private DialogInterface.OnClickListener getButtonListener() {
        return new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int i) {
                    goToGooglePlayStoreEntry();
                }
            };
    }

    private void goToGooglePlayStoreEntry() {
        context.startActivity(getAppListingIntent());
    }

    private Intent getAppListingIntent() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String pdfAppPackageName = "com.adobe.reader";
        intent.setData(Uri.parse("market://details?id=" + pdfAppPackageName));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    private Context context;

}