从我的应用程序打开的PDF文件无法共享

时间:2019-03-25 19:41:18

标签: android

在我的应用程序中,我从URL下载pdf文件,然后使用选择器打开该pdf文件。打开的文件无法共享。

这是我用来打开pdf文件的代码。

File file = new File(Environment.getExternalStoragePublicDirectory(                Environment.DIRECTORY_DOWNLOADS).toString()+"/oferte/oferta"+insertedid+".pdf");
File(getApplicationContext().getFilesDir().toString()+"/oferta"+idfactura+".pdf");
       Intent target = new Intent(Intent.ACTION_VIEW);
       target.setDataAndType(Uri.fromFile(file),"application/pdf");
       target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
       Intent intent = Intent.createChooser(target, "Open File");
       try {
           startActivity(intent);
           finish();
       } catch (ActivityNotFoundException e) {

       }

1 个答案:

答案 0 :(得分:0)

第一个应用必须具有READ_EXTERNAL_STORAGE权限。运行时请求(Android 6.0及更高版本)。链接https://developer.android.com/training/permissions/requesting.html

并且从android N共享文件到其他应用程序必须使用FileProvider。

编辑清单xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
        ...>
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${appPackageName}.fileprovider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths" />
        </provider>
        ...
    </application>
</manifest>

res / xml / filepaths.xml

<paths>
    <files-path path="files/" name="myfiles" />
</paths>

共享文件

    Intent target = new Intent(Intent.ACTION_VIEW);
    Uri fileUri;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        fileUri = FileProvider.getUriForFile(this,
                "appPackageName.fileprovider", file);
        target.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        target.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    } else {
        fileUri = Uri.fromFile(file);
    }
    target.setDataAndType(fileUri,"application/pdf");
    target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
    Intent intent = Intent.createChooser(target, "Open File");
    try {
        startActivity(intent);
        finish();
    } catch (ActivityNotFoundException e) {
    }

链接https://developer.android.com/training/secure-file-sharing/setup-sharing https://stackoverflow.com/a/38858040/4696538