我有以下代码,它仅适用于Android 7及更低版本。 Android 8只显示一个空白文件,我手动打开pdf并正常工作。
我有以下代码,这是repo:
private static final String SHARED_PROVIDER_AUTHORITY = BuildConfig.APPLICATION_ID + ".myfileprovider";
private static final String PDF_FOLDER = "pdf";
Bitmap bitmap = myCanvasView.getBitmap();
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.parseColor("#ffffff"));
canvas.drawPaint(paint);
bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
document.finishPage(page);
// write the document content
File file = null;
try {
file = createFile();
document.writeTo(new FileOutputStream(file));
} catch (IOException e) {
e.printStackTrace();
showToast("Something wrong: " + e.toString());
}
// close the document
document.close();
Uri uri = getUriFrom(file);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(uri,"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
其中:
@NonNull
private Uri getUriFrom(File file){
if(Build.VERSION.SDK_INT >= 26) {
return FileProvider.getUriForFile(getApplicationContext(), SHARED_PROVIDER_AUTHORITY, file);
}
else{
return Uri.fromFile(file);
}
}
@NonNull
private File createFile() throws IOException {
if(Build.VERSION.SDK_INT >= 26){
final File sharedFolder = new File(getFilesDir(), PDF_FOLDER);
sharedFolder.mkdirs();
final File sharedFile = File.createTempFile(getFilename(), ".pdf", sharedFolder);
sharedFile.createNewFile();
return sharedFile;
}
else{
return new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ getFilename());
}
}
答案 0 :(得分:3)
我找到了适合你的解决方案。只需在您的意图中添加标记Intent.FLAG_GRANT_READ_URI_PERMISSION
:
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(uri,"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
target.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
我刚刚在Pixel 2 XL和Android 8.1上使用你的回购测试了它并解决了这个问题:
让事情奏效:
希望这可以帮到你! :)