无法使用FileProvider打开pdf文件

时间:2018-09-15 15:12:38

标签: android android-intent

我彻底检查了pdf文件是否在 /storage/emulated/0/Download/20170802095833717678.pdf“ 但无法故意打开它。 为什么?我怎么了

androidmanifest.xml

<provider
        android:authorities="${applicationId}.provider"
        android:name="android.support.v4.content.FileProvider"
        android:exported="false"
        android:grantUriPermissions="true">

        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>

MainActivity.Java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent=new Intent();

    File file = new File("/storage/emulated/0/Download/20170802095833717678.pdf");
    Uri uri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", file);

    if (file.exists()) {
        Uri path = Uri.fromFile(file);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
             intent = new Intent(Intent.ACTION_VIEW);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }else{
            intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File("/storage/emulated/0/Download/20170802095833717678.pdf")));
        }


        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

 //  file:///storage/emulated/0/Download/20170802095833717678.pdf exposed beyond app through Intent.getData()
        try {
            startActivity(intent);
        }
        catch (ActivityNotFoundException e) {
            Log.e("error","error"+e);
        }
    }
}
}

res / xml / provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
 <paths xmlns:android="http://schemas.android.com/apk/res/android">
 <external-path
name="storage/emulated/0"
path="."/>
</paths>

1 个答案:

答案 0 :(得分:0)

尝试

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent=new Intent();

                    File mypath=new File( Environment.getexternalstoragedirectory(),"20170802095833717678.pdf");

                    Uri pdfUri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".provider", file);



    if (file.exists()) {
        Uri path = Uri.fromFile(file);
      Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(path , "application/pdf");
                    intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);


        try {
            startActivity(intent);
        }
        catch (ActivityNotFoundException e) {
            Log.e("error","error"+e);
        }
    }
}
}