I have used this code to download the pdf file in my app and it works well for all phones but the code I have written to open the downloaded file works well for APK less than 21 but it doesn't for better phones like Samsung S7 etc.
My code for downloading a pdf file:
Boolean memoerAvailable = (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED));
if (memoerAvailable) {
final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(link));
request.setTitle("Click to download the book");
request.setDescription("File is being downloaded...");
//use download manager to download the clicked book
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, ShowbooksActivity.myBooksList.get(ShowbooksActivity.pos).getMpdfName());
request.setDestinationInExternalFilesDir(bookWithAdapterActivity.this, Environment.DIRECTORY_DOWNLOADS, "myfile.jpg");
final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final long queueid = manager.enqueue(request);
My code for opening the downloaded file:
filetoopen = ls1.get(position);
File file = new File(Environment.getExternalStorageDirectory() +"/Download/" + filetoopen);
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(), "File not found", Toast.LENGTH_SHORT).show();
}
Do you have an exeption? Try to use FileProvier for API>23.
try this one
setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimeType,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading file...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition,
mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File",
Toast.LENGTH_LONG).show();
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.