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

Ric*_*rdo 2 android-fileprovider

我有以下代码,它仅适用于 Android 7 及更低版本。Android 8 只显示一个空白文件,我手动打开 pdf 并且工作正常。

我有以下代码,这是回购

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
}
Run Code Online (Sandbox Code Playgroud)

在哪里:

@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());
    }

}
Run Code Online (Sandbox Code Playgroud)

dni*_*Hze 5

我为您找到了解决方案。只需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);
Run Code Online (Sandbox Code Playgroud)

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

创建意图

并开始工作:

可以看文档

希望这可以帮助你!:)