在Android Q中使用mkdir无法创建文件夹

8

我的应用程序在所有 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();
        }

日志中有什么? - Rahul Khurana
@AhmadAyyaz 谢谢,但我的英语很弱,我无法理解该怎么做,你能告诉我应该做什么吗? - hadi khodabandeh
我的意思是,我们可能无法提供帮助,因为我们只能用英语提供帮助。 - Vladyslav Matviienko
@VladyslavMatviienko 我知道,但我无法在 developer.android 上阅读完整的文档。我很困惑,我只是想创建一个文件夹。 - hadi khodabandeh
日志中没有任何内容,因为您在catch块中没有像Log.e("DOWNLOAD","Exception: ".e.toString());这样的内容。请避免使用printStackTrace()。 - Abhinav Saxena
显示剩余4条评论
2个回答

10
 <manifest ... >
 <!-- This attribute is "false" by default on apps targeting Android Q. ->
  <application android:requestLegacyExternalStorage="true" ... >

 </application>
</manifest>

2
我认为值得一提的是,这只是一个热修补,一旦安卓R出现,它将不起作用! - FreakyAli
由于您的帮助,我已经解决了这个问题。谢谢。(适用于Android 10) - Mahmut K.

6

在Q中,如果您想访问不是常见的音乐或媒体文件,例如在您的情况下的sdcard/test文件,则需要执行以下操作:

为了访问任何其他应用程序创建的文件,其中包括“downloads”目录中的文件,您的应用程序必须使用"Storage Access Framework",该框架允许用户选择特定文件。

引用来源: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


2
文件夹的MIME类型是什么? - hadi khodabandeh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接