首页 > 解决方案 > 从我的应用程序打开的 PDF 文件无法共享

问题描述

在我的应用程序中,我从 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) {

       }

标签: android

解决方案


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

并且从android N 共享文件到其他app 必须使用FileProvider。</p>

编辑清单 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


推荐阅读