在牛轧糖上打开 PDF

Open PDF on Nougat

我有一个文件路径:file:///storage/emulated/0/Android/data/rocks.vd.*****.develop/files/1Q 2017年财务results.pdf

这是代码:

Intent intent = new Intent(Intent.ACTION_VIEW);
    try {
        String newFilePath = filePath.replaceAll("%20", " ");
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            intent.setDataAndType(Uri.parse(newFilePath), "application/pdf");
        } else {
            Uri uri = Uri.parse(newFilePath);
            File file = new File(uri.getPath());
            if (file.exists()){
                uri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
                intent.setDataAndType(uri, "application/pdf");
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
        }

        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        context.startActivity(intent);

我的uri = content://rocks.vd.*****.develop.provider/files/Android/data/rocks.vd .*****.develop/files/1Q%202017%20financial%20results.pdf

Pdf reader 打开时出现意外错误。 怎么了?

正在 Adob​​e pdf 中打开它 reader。如果未安装 adobe reader,我将重定向到 google 播放。

 private void viewPdf(Uri file){
Intent intent;
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(file, "application/pdf");
try{
startActivity(intent);
}catch(ActivityNotFoundException e){
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle("No Application Found");
builder.setMessage("Download from Android Market?");
builder.setPositiveButton("Yes, Please", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub

Intent marketIntent = new Intent(Intent.ACTION_VIEW);
marketIntent.setData(Uri.parse("market://details?id=com.adobe.reader"));
startActivity(marketIntent);

}
});
builder.setNegativeButton("No, Thanks", null);
builder.create().show();

}
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

在这里,您将清除所有现有标志,尤其是您的 FLAG_GRANT_READ_URI_PERMISSION。因此,您启动的 activity 将无法访问您的内容。

setFlags() 切换到 addFlags()

如果您使用 android-N(即上面的 API 24),请这样做

try {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    File f = new File(Your File Path);

    Uri uri = null;


    // So you have to use Provider
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        uri = FileProvider.getUriForFile(this,getApplicationContext().getPackageName() + ".provider", file);

        // Add in case of if We get Uri from fileProvider.
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }else{
        uri = Uri.fromFile(f);
    }

    intent.setDataAndType(uri, "application/pdf");
    startActivity(intent);
} catch(Exeption e){
    e.printstacktrace();
}

你也可以在 Lollipop 上面使用这段代码。