【问题标题】:Share file from my activity to another app using FileProvider not working使用 FileProvider 将文件从我的活动共享到另一个应用程序不起作用
【发布时间】:2016-08-26 13:52:34
【问题描述】:

我正在尝试使用 FileProvider 共享在我的应用程序中创建的 mp3 文件。我关注了documentationthis Stack Overflow post,但它不起作用:例如,gmail 说“无法附加空文件”。

mp3 文件保存在Environment.getExternalStorageDirectory()+"/MyApp"

我将提供程序添加到清单中:

<provider
   android:name="android.support.v4.content.FileProvider"
   android:authorities="com.myapp.fileprovider"
   android:exported="false"
   android:grantUriPermissions="true">
   <meta-data
       android:name="android.support.FILE_PROVIDER_PATHS"
       android:resource="@xml/file_provider_paths" />
</provider>

file_provider_paths.xml 添加到 res:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="share" path="MyApp/" />
</paths>

并将此方法添加到我的活动中:

public void ShowShareChooser(String filename)
{
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    File f = new File(filename);
    Uri fileUri = FileProvider.getUriForFile(this,"com.myapp.fileprovider",f);
    String type = getContentResolver().getType(fileUri);
    shareIntent.putExtra(Intent.EXTRA_STREAM,fileUri);
    shareIntent.setType(type);
    //shareIntent.setDataAndType(fileUri,type); // another failed attempt
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    shareIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    startActivity(Intent.createChooser(shareIntent, "Share song"));
}

filename"/storage/emulated/0/MyApp/Audio.mp3" 时,生成的fileUricontent://com.myapp.fileprovider/share/Audio.mp3typeaudio/mpeg

我的目标是 API 22,并在 Nexus 5 (6.0.1) 上进行测试。

【问题讨论】:

  • 作为测试尝试自己打开文件 uri 的输入流。
  • 您的应用是否缺少从外部存储读取的权限?
  • 谢谢大家,我只是笨。我固执地寻找这段代码中的错误,因为我在早期研究中读到,在没有 FileProvider 的情况下共享文件将不再有效。原来是代码另一个地方的新bug……

标签: android android-contentprovider android-sharing android-fileprovider


【解决方案1】:

事实证明,这对我来说是一个愚蠢的错误。由于代码中其他地方的新错误,该文件不再创建,而我认为它在那里。该代码确实可以正常工作,我将其留在这里以供将来参考(并作为个人纪念品)。

【讨论】:

    猜你喜欢
    • 2022-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    相关资源
    最近更新 更多