最近,我更新了一个应用程序,目标是sdk 30,并调整了使用mediastore创建和存储pdf的方式。对于创建和存储,我使用以下代码:
@RequiresApi(api = Build.VERSION_CODES.Q)
@NonNull
private Uri savePDFFile(@NonNull final Context context, @NonNull byte[] in,
@NonNull final String mimeType,
@NonNull final String displayName, @Nullable final String subFolder) throws IOException {
String relativeLocation = Environment.DIRECTORY_DOCUMENTS;
if (!TextUtils.isEmpty(subFolder)) {
relativeLocation += File.separator + subFolder;
}
final ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, displayName);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
final ContentResolver resolver = context.getContentResolver();
OutputStream stream = null;
Uri uri = null;
try {
final Uri contentUri = MediaStore.Files.getContentUri("external");
uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues);
ParcelFileDescriptor pfd;
try {
assert uri != null;
pfd = context.getContentResolver().openFileDescriptor(uri, "w");
assert pfd != null;
FileOutputStream out = new FileOutputStream(pfd.getFileDescriptor());
out.write(in);
out.close();
pfd.close();
} catch (Exception e) {
e.printStackTrace();
}
contentValues.clear();
contentValues.put(MediaStore.Video.Media.IS_PENDING, 0);
context.getContentResolver().update(uri, contentValues, null, null);
stream = resolver.openOutputStream(uri);
if (stream == null) {
throw new IOException("Failed to get output stream.");
}
return uri;
} catch (IOException e) {
// Don't leave an orphan entry in the MediaStore
resolver.delete(uri, null, null);
throw e;
} finally {
if (stream != null) {
stream.close();
renderPDF(this.fileName, this.fileType);
}
}
}
pdf存储在/storage/emulated/0/download中,保存后,我希望通过intent呈现它
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
File file = new File(path.toString() + "/" + fileName + "." + filetype);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.setDataAndType(FileProvider.getUriForFile(this, getPackageName() + ".provider",file), "application/pdf");
我的provider_paths.xml设置如下:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external"
path="Download/" />
<external-files-path
name="external_files"
path="Download/" />
<files-path
name="files"
path="Download/" />
</paths>
此时,当您下载pdf时,会显示您要选择的pdf阅读器,当您选择其中一个阅读器时,会显示一条消息错误,表示路径太长(如果google drive pdf阅读器在一毫秒内显示一个空白屏幕,然后再次返回应用程序。
如何通过fileprovider检索pdf文件并启动intent?我认为现在的问题在于文件提供程序,但我不知道如何。。。
intent.setDataAndType(FileProvider.getUriForFile(this, getPackageName() + ".provider",file), "application/pdf");
暂无答案!
目前还没有任何答案,快来回答吧!