android baixar pdf do url e abri-lo com um leitor de pdf
Estou tentando escrever um aplicativo para baixar PDFs de url, armazená-los em sd e, em seguida, abrir pelo Adobe PDF Reader ou outros aplicativos que possam abrir o PDF.
até agora, eu tinha "baixado e armazenado com sucesso no cartão SD" (mas sempre que tento abrir o pdf com um leitor de pdf, travamento do leitor e dizer que ocorre um erro inesperado), por exemplo,http://maven.apache.org/maven-1.x/maven.pdf
Aqui está o código para o meu downloader:
//........code set ui stuff
//........code set ui stuff
new DownloadFile().execute(fileUrl, fileName);
private class DownloadFile extends AsyncTask<String, Void, Void>{
@Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0]; // -> http://maven.apache.org/maven-1.x/maven.pdf
String fileName = strings[1]; // -> maven.pdf
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "testthreepdf");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
return null;
}
}
public class FileDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
no modo de depuração, posso ver o aplicativo baixado e armazenar este pdf em /storage/sdcard/testpdf/maven.pdf, no entanto, acho que o arquivo pode estar corrompido de alguma forma durante o download, por isso não é aberto corretamente ...
Aqui está o código de como pretendo abri-lo com outro aplicativo leitor:
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + fileName); // -> filename = maven.pdf
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try{
startActivity(pdfIntent);
}catch(ActivityNotFoundException e){
Toast.makeText(documentActivity, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}