问题
I try to open PDF file in Pie? but it does not open. I don't get any error. What is the issue? PDF file does not open. Only black screen is shown. In logcat no errors show. What is wrong?
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri outputFileUri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
outputFileUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file);
} else
outputFileUri = Uri.fromFile(file);
Log.e("TAG", "outputFileUri-> " + outputFileUri);
intent.setDataAndType(outputFileUri, "application/pdf");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No Application available to view pdf", Toast.LENGTH_LONG).show();
}
AndroidManifest.xml
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
<paths>
<external-path
name="external_files"
path="." />
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<cache-path
name="cache"
path="." />
<external-cache-path
name="external_cache"
path="." />
<files-path
name="files"
path="." />
How Can I resolve this issue? I referred many links but did not get solution. I also tried many codes but no help.
回答1:
File dwldsPath = new File((Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "test.pdf"));`enter code here`
byte[] pdfAsBytes = Base64.decode(content, 0);
`enter code here` FileOutputStream os;
os = new FileOutputStream(dwldsPath, false);
os.write(pdfAsBytes);
os.flush();
os.close();
if (dwldsPath.exists()) {
Uri path = Uri.fromFile(dwldsPath);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// If requesting from a fragment...
this.startActivity(intent);
return;
}
来源:https://stackoverflow.com/questions/57933151/how-to-open-pdf-file-from-internal-storage-in-pie