Android Studio 档案提供者:找不到已配置的根目录

yrwegjxp  于 2022-11-16  发布在  Android
关注(0)|答案(2)|浏览(119)

我一直在尝试共享一个pdf文件,我这样设置FileProvider:
在主清单xml上:

<provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>

res/xml/file_paths.xml档案:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path name="my_files" path="." />
</paths>

在我的代码中,我尝试以下操作:

String path = root.getAbsolutePath() + "/file.pdf";
final Uri data = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID+".fileprovider", new File(path));
getApplicationContext().grantUriPermission(getApplicationContext().getPackageName(), data, Intent.FLAG_GRANT_READ_URI_PERMISSION);
final Intent intent = new Intent(Intent.ACTION_VIEW).setDataAndType(data, "application/pdf").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
getApplicationContext().startActivity(intent);

返回错误:

Caused by: java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/file.pdf
i2loujxw

i2loujxw1#

The documentation for FileProvider表示<files-path>
表示应用内部存储区域的files/子目录中的文件。此子目录与Context.getFilesDir()返回的值相同。
您的文件不在internal storage中。它在external storage中。为此,您需要<external-path>元素,而不是<files-path>元素。

f1tvaqid

f1tvaqid2#

公认的答案是正确的,但他没有指定要使用的API,所以下面就是它。

val imagePath = File(
    Environment.getExternalStorageDirectory().path +
            File.separator, "Your folder name"
)
val newfile = File(imagePath, "Your file name")

val imageUri = FileProvider.getUriForFile(
    context,
    "com.example.domain.provider",
    newfile
)
val shareIntent = Intent(Intent.ACTION_SEND)
shareIntent.type = "image/jpg" // set file type 
shareIntent.putExtra(
    Intent.EXTRA_STREAM,
    imageUri
)
context.startActivity(Intent.createChooser(shareIntent, "Share Status Saver Image"))

快乐编码!

相关问题