Downloading A Pdf And Displaying It (fileuriexposedexception)
As a preface, I am familiar with coding (2 years in highschool) but am a complete novice when it comes to Android Studio (and Java, in general). I've been searching for solutions f
Solution 1:
If your targetSdkVersion >= 24, then we have to use FileProvider class to give access to the particular file or folder to make them accessible for other apps.
1) First Add a FileProvider tag in AndroidManifest.xml under tag as below:
<?xml version="1.0" encoding="utf-8"?><manifestxmlns:android="http://schemas.android.com/apk/res/android"...
<application...
<providerandroid:name=".GenericFileProvider"android:authorities="${applicationId}.my.package.name.provider"android:exported="false"android:grantUriPermissions="true"><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/provider_paths"/></provider></application></manifest>
2) Then create a provider_paths.xml file in res/xml folder. Folder may be needed to created if it doesn't exist.
<paths><external-pathname="external_files"path="."/></paths>
3) Now create PdfDownload.java class file and paste below code:
publicclassPdfDownloadextendsActivity {
TextView tv_loading;
Context context;
intdownloadedSize=0, totalsize;
floatper=0;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
isStoragePermissionGranted();
super.onCreate(savedInstanceState);
tv_loading = newTextView(this);
tv_loading.setGravity(Gravity.CENTER);
tv_loading.setTypeface(null, Typeface.BOLD);
setContentView(tv_loading);
downloadAndOpenPDF();
}
publicstatic String getLastBitFromUrl(final String url) {
return url.replaceFirst(".*/([^/?]+).*", "$1");
}
voiddownloadAndOpenPDF() {
finalStringdownload_file_url= getIntent().getStringExtra("url");
newThread(newRunnable() {
publicvoidrun() {
Uripath= Uri.fromFile(downloadFile(download_file_url));
try {
Intentintent=newIntent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uriuri= FileProvider.getUriForFile(PdfDownload.this, BuildConfig.APPLICATION_ID, downloadFile(download_file_url));
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
finish();
} catch (ActivityNotFoundException e) {
tv_loading
.setError("PDF Reader application is not installed in your device");
}
}
}).start();
}
File downloadFile(String dwnload_file_path) {
Filefile=null;
try {
URLurl=newURL(dwnload_file_path);
HttpURLConnectionurlConnection= (HttpURLConnection) url
.openConnection();
urlConnection.connect();
Stringtest= getLastBitFromUrl(dwnload_file_path);
Stringdest_file_path= test.replace("%20", "_");
// set the path where we want to save the fileFileSDCardRoot= Environment.getExternalStorageDirectory();
// // create a new file, to save the downloaded file
file = newFile(SDCardRoot, dest_file_path);
if (file.exists()) {
return file;
}
FileOutputStreamfileOutput=newFileOutputStream(file);
// Stream used for reading the data from the internetInputStreaminputStream= urlConnection.getInputStream();
// this is the total size of the file which we are// downloading
totalsize = urlConnection.getContentLength();
setText("Starting PDF download...");
// create a buffer...byte[] buffer = newbyte[1024 * 1024];
intbufferLength=0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
per = ((float) downloadedSize / totalsize) * 100;
if ((totalsize / 1024) <= 1024) {
setText("Total PDF File size : " + (totalsize / 1024)
+ " KB\n\nDownloading PDF " + (int) per + "% complete");
} else {
setText("Total PDF File size : " + (totalsize / 1024) / 1024
+ " MB\n\nDownloading PDF " + (int) per + "% complete");
}
// setText("configuring your book pleease wait a moment");
}
// close the output stream when complete //
fileOutput.close();
// setText("Download Complete. Open PDF Application installed in the device.");
setText("configuaration is completed now your book is ready to read");
} catch (final MalformedURLException e) {
setTextError("Some error occured. Press back and try again.",
Color.RED);
} catch (final IOException e) {
setTextError("Some error occured. Press back and try again.",
Color.RED);
} catch (final Exception e) {
setTextError(
"Failed to download image. Please check your internet connection.",
Color.RED);
}
return file;
}
voidsetTextError(final String message, finalint color) {
runOnUiThread(newRunnable() {
publicvoidrun() {
tv_loading.setTextColor(color);
tv_loading.setText(message);
}
});
}
voidsetText(final String txt) {
runOnUiThread(newRunnable() {
publicvoidrun() {
tv_loading.setText(txt);
}
});
}
privatestaticfinalStringTAG="MyActivity";
publicbooleanisStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission is granted");
returntrue;
} else {
Log.v(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, newString[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
returnfalse;
}
} else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG, "Permission is granted");
returntrue;
}
}
@OverridepublicvoidonRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission: " + permissions[0] + "was " + grantResults[0]);
}
}
}
Post a Comment for "Downloading A Pdf And Displaying It (fileuriexposedexception)"