繁体   English   中英

Android中的文件共享

[英]File Sharing in Android

我是使用android开发的新手,最近正在使用将文档导出为PDF(转换)工具的android应用程序,问题是在导出PDF之后,我想给用户一个通过意图共享文档(PDF)的选项,我在stackoverflow周围进行了挖掘,但无法理解,答案实际上并未回答我的问题。 PDF已导出/创建到外部SD卡中。

我已经在导出/创建PDF后通过应用程序创建了一个PDF,我想通过Intent共享它们,我在stackoverflow上进行了挖掘,但是得到了答案。我如何通过Intent共享它,就像我与Image,通过Intent分享文本一样。


您可以使用ACTION_SEND激活指定文件类型的选择器,只需记住提供“ application / pdf”作为文件类型。

public void SharePdf(File file) {
    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
    shareIntent.setType("application/pdf");
    startActivity(Intent.createChooser(shareIntent, "Share PDF"));
}

现在调用SharePdf(new File(fileName))来启动意图,并让用户选择正确的选项。

用户@oleonardomachado的回答是正确的,但是从android N更新禁止直接uri共享。 您必须使用文件提供程序来获取uri数据,然后进行共享。

使用意图分享

Intent shareIntent = new Intent();

shareIntent.setAction(Intent.ACTION_SEND);

if (Build.VERSION.SDK_INT >= 24) {
    Uri fileUri = FileProvider.getUriForFile(getContext(), getPackageName()+".fileprovider", file); // provider app name

    shareIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
    shareIntent.setType("application/pdf");
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
    shareIntent.setType("application/pdf");
}

startActivity(Intent.createChooser(shareIntent, "Share PDF"));

在AndroidManifest.xml中

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    <application
        ...
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.my.package.name.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"/>
        </provider>
    </application>
</manifest>

然后在res / xml文件夹中创建一个file_paths.xml文件。 xml文件夹可能不存在,因此如果不存在,请创建。 该文件的内容如下所示。 它描述了我们希望共享对根目录(path =“。”)上的外部存储的访问。

file_paths.xml

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

希望这对其他人有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM