Я пытаюсь написать приложение для загрузки pdf файлов из url, хранить их на sd, затем открывать Adobe Reader или другие приложения, которые когда-либо могли открыть pdf.
до сих пор я "успешно загрузил и сохранил его на Sd-карте" (но каждый раз, когда я пытаюсь открыть PDF файл с помощью PDF-ридера, сбой читателя и скажем непредвиденная ошибка), например, http://maven.apache.org/maven-1.x/maven.pdf
вот код для моего загрузчика:
//........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();
}
}
}
в режиме отладки, я могу увидеть, как приложение загрузило его и сохранит этот файл pdf на /storage/sdcard/testpdf/maven.pdf, однако я думаю, что файл может быть поврежден каким-то образом во время загрузки, поэтому он не открывается должным образом...
вот код, как я намерен открыть его с другим приложением для чтения:
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();
}