2010-09-14 25 views
7

En mi onCreate() hago esta comprobación:Mostrar PDF en Android

// 
// check if we have a PDF viewer, else bad things happen 
// 
Intent intent = new Intent(Intent.ACTION_VIEW); 
intent.setType("application/pdf"); 

List<ResolveInfo> intents = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); 

if (intents == null || intents.size() == 0) { 
     // display message then... 
     finish(); 
} 

En mi HTC Desire, esto no devolver un partido, a pesar de que tengo visor de PDF de Adobe. Una respuesta a esta pregunta android: open a pdf from my app using the built in pdf viewer menciona que Adobe puede no tener ningún Intento público, por lo que la verificación anterior obviamente no arrojará nada.

¿Alguien puede verificar si puede iniciar Acrobat desde un intento, o hay algún otro método o visor de PDF para usar?

El caso de uso real está descargando copias de las facturas y almacenarlos en el almacenamiento local utilizando un código como:

URL url = new URL(data); 
InputStream myInput = url.openConnection().getInputStream(); 

FileOutputStream fos = openFileOutput(fname, Context.MODE_WORLD_READABLE); 

// transfer bytes from the input file to the output file 
byte[] buffer = new byte[8192]; 
int length; 
while ((length = myInput.read(buffer)) > 0) { 
    fos.write(buffer, 0, length); 
    progressDialog.setProgress(i++); 
} 
fos.close(); 

y luego para mostrar

// read from disk, and call intent 
openFileInput(fname); // will throw FileNotFoundException 

File dir = getFilesDir();  // where files are stored 
File file = new File(dir, fname); // new file with our name 

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file)); 
intent.setType("application/pdf"); 

startActivity(intent); 

Respuesta

6

Conecte el teléfono a su PC, inicio Eclipse y abra el LogCat. A continuación, descargue un archivo PDF con el navegador y ábralo. Debería ver una línea como (utilicé el deseo de HTC):

09-14 17: 45: 58.152: INFO/ActivityManager (79): Actividad de inicio: Intención {act = android.intent.action.VIEW dat = file: ///sdcard/download/FILENAME.pdf typ = application/pdf flg = 0x4000000 cmp = com.htc.pdfreader/.ActPDFReader}

Inicie sesión con un intento explícito utilizando la información del componente. Documentos dicen aquí:

> componente - Especifica un nombre explícito de una clase de componente a utilizar para el intento. Normalmente esto se determina al mirar la otra información en la intención (la acción, el tipo de datos y las categorías) y hacerla coincidir con un componente que pueda manejarla. Si se establece este atributo, no se realiza ninguna evaluación, y este componente se usa exactamente como está. Al especificar este atributo, todos los demás atributos de intención se vuelven opcionales.

Downside está usted obligado al lector htc. Pero podría probar primero un intento implícito y, si eso falla, probar el intento explícito como una reserva.

+1

Gracias - buena idea – BJB

0

-Copie el siguiente código en su actividad. Llame a la función CopyReadAssets ("File_name.pdf") de la función onCreate(). Coloque el archivo File_name.pdf en la carpeta de activos.

private void CopyReadAssets(String pdfname) 
{ 
    AssetManager assetManager = getAssets(); 
    InputStream in = null; 
    OutputStream out = null; 
    File file = new File(getFilesDir(), pdfname); 
    try 
    { 
     in = assetManager.open(pdfname); 
     out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE); 
     copyFile(in, out); 
     in.close(); 
     in = null; 
     out.flush(); 
     out.close(); 
     out = null; 
    } catch (Exception e) 
    { 
     Toast.makeText(getApplicationContext(), "Pdf Viewer not installed", Toast.LENGTH_SHORT).show(); 
    } 
    try 
    { 
    Intent intent = new Intent(Intent.ACTION_VIEW); 
    intent.setDataAndType(
      Uri.parse("file://" + getFilesDir() + "/"+pdfname), 
      "application/pdf"); 

    startActivity(intent); 
    }catch (Exception e) { 
     // TODO: handle exception 
     Toast.makeText(getApplicationContext(), "Pdf Viewer not installed" ,Toast.LENGTH_SHORT).show(); 
    } 
} 

private void copyFile(InputStream in, OutputStream out) throws IOException 
{ 
    byte[] buffer = new byte[1024]; 
    int read; 
    while ((read = in.read(buffer)) != -1) 
    { 
     out.write(buffer, 0, read); 
    } 
}