2012-05-10 28 views
34

Estoy tratando de abrir un archivo Intent para abrir un pdf dentro de la carpeta de mis activos en mi aplicación. He leído docenas de publicaciones pero aún estoy atascado. Aparentemente necesito copiar el pdf a la tarjeta sd primero y luego ejecutar un Intent. Todavía no funciona.Cómo abrir un PDF mediante Intent desde la tarjeta SD

Creo que el problema es la Intent lanzamiento por lo que simplemente estoy tratando de abrir un archivo "ejemplo.pdf" que he copiado en la tarjeta SD utilizando este código:

Log.w("IR", "TRYING TO RENDER: " + Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf"); 
Intent intent = new Intent(Intent.ACTION_VIEW); 
intent.setDataAndType(Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf"), "application/pdf"); 
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

try { 
    startActivity(intent); 
    Log.e("IR", "No exception"); 
} 
catch (ActivityNotFoundException e) { 
    Log.e("IR", "error: " + e.getMessage()); 
    Toast.makeText(InvestorRelations.this, 
     "No Application Available to View PDF", 
     Toast.LENGTH_SHORT).show(); 
} 

Ésta es mi salida LogCat .

05-10 10:35:10.950: W/IR(4508): TRYING TO RENDER: /mnt/sdcard/example.pdf 
05-10 10:35:10.960: E/IR(4508): No exception 

Excepto cuando se ejecuta este código, me sale el siguiente tostadas (no producido por mi aplicación)

"No es un apoyada tipo de documento"

Pero puedo abrir el documento manualmente a través de la Aplicación de visualización de PDF instalada. Cualquier ayuda sería muy apreciada.

Respuesta

96

probar este código, archivo PDF a partir de pantalla/sdcard

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf"); 
Intent intent = new Intent(Intent.ACTION_VIEW); 
intent.setDataAndType(Uri.fromFile(file), "application/pdf"); 
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); 
startActivity(intent); 
+2

Gracias por poner fin a mi búsqueda. ¿Por qué funciona eso en vez de analizar la URL de un String? –

+1

¿Cómo puedo pasar a la página particular en particular? ¿hay alguna manera? –

+0

@PratikButani - Como está utilizando una aplicación pdf de terceros para abrir un archivo PDF, no puede manejar la navegación de página en pdf para ninguna página en particular. – user370305

0

Puede tener algo que ver con el hecho de que los archivos de la carpeta de los activos se comprimen.

Intente moverlo a su carpeta res/raw/.

Más información: https://stackoverflow.com/a/4432804/413127

+0

Ni siquiera estoy tratando de ver el pdf de mi aplicación. Usé mi sistema operativo para copiar un pdf a la tarjeta SD y todavía no puedo verlo a través de un intento –

3

descargar el código fuente desde aquí (Open pdf file from sdcard in android programmatically)

Añadir esta dependencia:

compile ‘com.github.barteksc:android-pdf-viewer:2.0.3’ 

activity_main.xml:

<?xml version=”1.0″ encoding=”utf-8″?> 
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221; 
xmlns:tools=”http://schemas.android.com/tools&#8221; 
android:id=”@+id/activity_main” 
android:layout_width=”match_parent” 
android:layout_height=”match_parent” 
android:background=”#efefef”> 

<ListView 
android:layout_width=”match_parent” 
android:id=”@+id/lv_pdf” 
android:divider=”#efefef” 
android:layout_marginLeft=”10dp” 
android:layout_marginRight=”10dp” 
android:layout_marginTop=”10dp” 
android:layout_marginBottom=”10dp” 
android:dividerHeight=”5dp” 
android:layout_height=”wrap_content”> 

</ListView> 
</RelativeLayout> 

MainActivity.java:

package com.pdffilefromsdcard; 

import android.Manifest; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.content.pm.PackageManager; 
import android.os.Environment; 
import android.support.v4.app.ActivityCompat; 
import android.support.v4.content.ContextCompat; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.ListView; 
import android.widget.Toast; 

import java.io.File; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 

public class MainActivity extends AppCompatActivity { 

ListView lv_pdf; 
public static ArrayList<File> fileList = new ArrayList<File>(); 
PDFAdapter obj_adapter; 
public static int REQUEST_PERMISSIONS = 1; 
boolean boolean_permission; 
File dir; 

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

} 

private void init() { 

lv_pdf = (ListView) findViewById(R.id.lv_pdf); 
dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()); 
fn_permission(); 
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
@Override 
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { 
Intent intent = new Intent(getApplicationContext(), PdfActivity.class); 
intent.putExtra(“position”, i); 
startActivity(intent); 

Log.e(“Position”, i + “”); 
} 
}); 
} 

public ArrayList<File> getfile(File dir) { 
File listFile[] = dir.listFiles(); 
if (listFile != null && listFile.length > 0) { 
for (int i = 0; i < listFile.length; i++) { 

if (listFile[i].isDirectory()) { 
getfile(listFile[i]); 

} else { 

boolean booleanpdf = false; 
if (listFile[i].getName().endsWith(“.pdf”)) { 

for (int j = 0; j < fileList.size(); j++) { 
if (fileList.get(j).getName().equals(listFile[i].getName())) { 
booleanpdf = true; 
} else { 

} 
} 

if (booleanpdf) { 
booleanpdf = false; 
} else { 
fileList.add(listFile[i]); 

} 
} 
} 
} 
} 
return fileList; 
} 
private void fn_permission() { 
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) { 

if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) { 
} else { 
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 
REQUEST_PERMISSIONS); 

} 
} else { 
boolean_permission = true; 

getfile(dir); 

obj_adapter = new PDFAdapter(getApplicationContext(), fileList); 
lv_pdf.setAdapter(obj_adapter); 

} 
} 

@Override 
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
if (requestCode == REQUEST_PERMISSIONS) { 

if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

boolean_permission = true; 
getfile(dir); 

obj_adapter = new PDFAdapter(getApplicationContext(), fileList); 
lv_pdf.setAdapter(obj_adapter); 

} else { 
Toast.makeText(getApplicationContext(), “Please allow the permission”, Toast.LENGTH_LONG).show(); 

} 
} 
} 

} 

activity_pdf.xml:

<?xml version=”1.0″ encoding=”utf-8″?> 
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221; 
android:layout_width=”match_parent” 
android:background=”#ffffff” 
android:layout_height=”match_parent” 
android:orientation=”vertical”> 

<com.github.barteksc.pdfviewer.PDFView 
android:id=”@+id/pdfView” 
android:layout_margin=”10dp” 
android:layout_width=”match_parent” 
android:layout_height=”match_parent” /> 
</LinearLayout> 

PdfActivity.java:

paquete com.pdffilefromsdcard;

import android.os.Bundle; 
import android.support.annotation.Nullable; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 

import com.github.barteksc.pdfviewer.PDFView; 
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener; 
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener; 
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle; 
import com.shockwave.pdfium.PdfDocument; 

import java.io.File; 
import java.util.List; 

public class PdfActivity extends AppCompatActivity implements OnPageChangeListener,OnLoadCompleteListener { 

PDFView pdfView; 
Integer pageNumber = 0; 
String pdfFileName; 
String TAG=”PdfActivity”; 
int position=-1; 

@Override 
protected void onCreate(@Nullable Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_pdf); 
init(); 
} 

private void init(){ 
pdfView= (PDFView)findViewById(R.id.pdfView); 
position = getIntent().getIntExtra(“position”,-1); 
displayFromSdcard(); 
} 

private void displayFromSdcard() { 
pdfFileName = MainActivity.fileList.get(position).getName(); 

pdfView.fromFile(MainActivity.fileList.get(position)) 
.defaultPage(pageNumber) 
.enableSwipe(true) 

.swipeHorizontal(false) 
.onPageChange(this) 
.enableAnnotationRendering(true) 
.onLoad(this) 
.scrollHandle(new DefaultScrollHandle(this)) 
.load(); 
} 
@Override 
public void onPageChanged(int page, int pageCount) { 
pageNumber = page; 
setTitle(String.format(“%s %s/%s”, pdfFileName, page + 1, pageCount)); 
} 
@Override 
public void loadComplete(int nbPages) { 
PdfDocument.Meta meta = pdfView.getDocumentMeta(); 
printBookmarksTree(pdfView.getTableOfContents(), “-“); 

} 

public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) { 
for (PdfDocument.Bookmark b : tree) { 

Log.e(TAG, String.format(“%s %s, p %d”, sep, b.getTitle(), b.getPageIdx())); 

if (b.hasChildren()) { 
printBookmarksTree(b.getChildren(), sep + “-“); 
} 
} 
} 
} 

Gracias!

0

Para Android Nougat y la versión anterior de Android hay que hacer algo más, de lo contrario, la aplicación no podrá abrir el archivo .pdf.Tenemos que establecer un permiso temporal para URI usando FileProvider

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 
    File file=new File(mFilePath); 
    Uri uri = FileProvider.getUriForFile(this, getPackageName() + ".provider", file); 
    intent = new Intent(Intent.ACTION_VIEW); 
    intent.setData(uri); 
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 
    startActivity(intent); 
    } else { 
    intent = new Intent(Intent.ACTION_VIEW); 
    intent.setDataAndType(Uri.parse(mFilePath), "application/pdf"); 
    intent = Intent.createChooser(intent, "Open File"); 
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    startActivity(intent); 
    } 
Cuestiones relacionadas