gpt4 book ai didi

android-fileprovider - Android 8 - FileProvider Uri 打开一个空白屏幕

转载 作者:行者123 更新时间:2023-12-05 01:17:31 25 4
gpt4 key购买 nike

我有以下代码,它只适用于 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());
}

}

最佳答案

我为您找到了解决方案。只需将标志 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);

我刚刚在带有 Android 8.1 的 Pixel 2 XL 上使用您的 repo 对其进行了测试,并解决了这个问题:

Creating intent

一切顺利:

Can see the document

希望对您有所帮助! :)

关于android-fileprovider - Android 8 - FileProvider Uri 打开一个空白屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49861087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com