【问题标题】:Cant Create Folder in Android Q with mkdir无法在 Android Q 中使用 mkdir 创建文件夹
【发布时间】:2019-07-05 07:44:53
【问题描述】:

我的应用在所有 android 版本中创建文件夹都没有问题,除了 android Q ,我不知道为什么我的代码在 android 中不起作用 q

这是我的代码:

File dir = new File("/sdcard/test");
       try{
              if(dir.mkdir()) {
                      Log.d("DOWNLOAD","Directory created");
              } else {
                     Log.d("DOWNLOAD","Directory is not created");
              }
            }catch(Exception e){
                  e.printStackTrace();
        }

【问题讨论】:

  • logcat 中有什么?
  • 请看developer.android.com/preview/privacy/scoped-storage谷歌在android Q中引入了Scoped Storage
  • @AhmadAyyaz tnx 但是我的英语很弱我不知道该怎么办,你能告诉我该怎么办吗?
  • @RahulKhurana logcat 中什么都没有
  • my english is weak StackOverflow 的这一部分只有英文

标签: java android mkdir android-10.0


【解决方案1】:
 <manifest ... >
 <!-- This attribute is "false" by default on apps targeting Android Q. ->
  <application android:requestLegacyExternalStorage="true" ... >

 </application>
</manifest>

【讨论】:

  • 我认为值得一提的是,这只是一个修补程序,一旦 Android R 出现,它将无法工作!
  • 感谢您,我摆脱了这个问题。谢谢。 (适用于 Android 10)
【解决方案2】:

在 Q 中,如果您想要访问不是普通音乐或媒体文件的文件,即在您的情况下为 sdcard/test,那么您需要执行以下操作:

为了访问其他应用创建的任何其他文件,包括“下载”目录中的文件,您的应用必须使用存储访问框架,该框架允许用户选择特定文件。

引用源:http://developer.android.com/preview/privacy/scoped-storage

// Here are some examples of how you might call this method.
// The first parameter is the MIME type, and the second parameter is the name
// of the file you are creating:
//
// createFile("text/plain", "foobar.txt");
// createFile("image/png", "mypicture.png");

// Unique request code.
private const val WRITE_REQUEST_CODE: Int = 43
...
private fun createFile(mimeType: String, fileName: String) {
    val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
        // Filter to only show results that can be "opened", such as
        // a file (as opposed to a list of contacts or timezones).
        addCategory(Intent.CATEGORY_OPENABLE)

        // Create a file with the requested MIME type.
        type = mimeType
        putExtra(Intent.EXTRA_TITLE, fileName)
    }

    startActivityForResult(intent, WRITE_REQUEST_CODE)
}

示例源代码https://developer.android.com/guide/topics/providers/document-provider

【讨论】:

  • 什么是文件夹的 mimetype?
猜你喜欢
  • 2014-11-30
  • 2010-11-22
  • 2011-08-22
  • 2022-12-03
  • 1970-01-01
  • 1970-01-01
  • 2020-06-08
  • 2019-05-05
  • 2016-09-25
相关资源
最近更新 更多