【问题标题】:what is the right way to write to a temp file which can be read from other app什么是写入可以从其他应用程序读取的临时文件的正确方法
【发布时间】:2015-08-29 03:12:52
【问题描述】:

它需要生成一个临时文件并通过其他可能的应用程序共享:

Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(filePath)));
startActivity(Intent.createChooser(intent, "share file");

但是当与其他应用程序共享时,文件似乎无法访问。这是因为文件保存在应用程序内部目录中。

所以它需要保存到属于这个应用程序的目录(所以它会在卸载时被删除,最好是在一个临时目录中,以便操作系统可以清理它),并且其他应用程序也可以访问它。

看到 getExternalCacheDir()、getExternalFilesDir()、getExternalStorageDirectory()、getExternalStoragePublicDirectory(),不确定哪种方法适合这种情况。有人有建议吗?谢谢!

【问题讨论】:

    标签: android file local-storage share


    【解决方案1】:

    在应用程序之间共享文件的安全方式是通过FileProvider:有关详细信息,请参阅these Android docs

    但他们也有一个关于how to make world-writable files 的部分,通过Environment.getExternalStoragePublicDirectory

    【讨论】:

    • 感谢您的建议。但不想去 FileProvider 溃败。 Environment.getExternalStoragePublicDirectory 的问题在于它在应用程序的数据路径之外。 FLAG_GRANT_READ_URI_PERMISSION 对这种情况有用吗?
    • 抱歉,我错过了关于您希望将文件放在自己应用程序目录中的部分。
    • 在这种情况下,使用getExternalFilesDir 将文件写入您自己的应用程序,然后在发送Intent 时使用FLAG_GRAN_READ_URI_PERMISSION。请参阅here 了解更多信息。
    • 使用 FLAG_GRAN_READ_URI_PERMISSION 似乎有人担心人们报告此标志不能始终如一地工作。
    【解决方案2】:

    我找不到将其保留在应用程序路径中的方法。所以我正在使用 getExternalStorageDirectory。

    File dataFolder = new File(Environment.getExternalStorageDirectory(), "myfolder");
        dataFolder.mkdirs();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      • 2014-10-29
      • 1970-01-01
      • 2011-11-16
      相关资源
      最近更新 更多