无法使用FileProvider打开pdf文件

问题描述 投票:0回答:1

我彻底检查了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>

main activity.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>
android android-intent
1个回答
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);
        }
    }
}
}
© www.soinside.com 2019 - 2024. All rights reserved.