英文:
how to view file saved via content Content Resolver
问题
I have saved a PDF file to the documents directory using contentResolver. it is getting saved successfully. However, I'm not able to open the file via code.
以下是代码部分:
public void saveToExternalStorage(File file, Context context) {
ContentValues cv = new ContentValues();
cv.put(MediaStore.Files.FileColumns.DISPLAY_NAME, "order" + new Date().getTime() + ".pdf");
cv.put(MediaStore.Files.FileColumns.MIME_TYPE, "application/pdf");
cv.put(MediaStore.Files.FileColumns.RELATIVE_PATH, "Documents");
cv.put(MediaStore.Files.FileColumns.IS_PENDING, 1);
ContentResolver resolver = context.getContentResolver();
Uri uri = resolver.insert(MediaStore.Files.getContentUri("external"), cv);
if (uri != null) {
try {
OutputStream outputStream = resolver.openOutputStream(uri);
byte[] bytes = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytes);
outputStream.write(bytes);
outputStream.close();
Log.e("file", "saved" + uri);
cv.put(MediaStore.Downloads.IS_PENDING, 0);
resolver.update(uri, cv, null, null);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
context.startActivity(intent);
} catch (Exception e) {
Log.e("error", Log.getStackTraceString(e.fillInStackTrace()));
}
}
}
模拟器打开一个带有空白屏幕的应用程序。
英文:
I have saved a PDF file to the documents directory using contentResolver. it is getting saved successfully. However, I'm not able to open the file via code.
following is the code
public void saveToExternalStorage(File file, Context context) {
ContentValues cv = new ContentValues();
cv.put(MediaStore.Files.FileColumns.DISPLAY_NAME, "order" + new Date().getTime() + ".pdf");
cv.put(MediaStore.Files.FileColumns.MIME_TYPE, "application/pdf");
cv.put(MediaStore.Files.FileColumns.RELATIVE_PATH, "Documents");
cv.put(MediaStore.Files.FileColumns.IS_PENDING, 1);
ContentResolver resolver = context.getContentResolver();
Uri uri = resolver.insert(MediaStore.Files.getContentUri("external"), cv);
if (uri != null) {
try {
OutputStream outputStream = resolver.openOutputStream(uri);
byte[] bytes = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytes);
outputStream.write(bytes);
outputStream.close();
Log.e("file", "saved" + uri);
cv.put(MediaStore.Downloads.IS_PENDING, 0);
resolver.update(uri, cv, null, null);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
context.startActivity(intent);
} catch (Exception e) {
Log.e("error", Log.getStackTraceString(e.fillInStackTrace()));
}
}
}
答案1
得分: 1
唯一需要添加的是在意图中添加一个读取权限标志。
英文:
The only thing you need to add is a READ permission flag to the intent.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论