存储访问框架 - 获取可用存储

时间:2016-02-29 14:03:44

标签: android storage-access-framework

我可以以某种方式找出当前可用的存储空间而无需启动文档选择器并让用户选择目录吗?

我想显示所有存储根,如下所示:

  <xsl:template match="tag[@k='ID']">
    <tag k="test" value="{@v}"/>
  </xsl:template>

为什么吗

实际上我想知道SD卡是否可用,然后告诉用户他需要通过文件选择器选择SD卡根目录...

所以我想要关注:

  1. 检查SD卡是否可用
  2. 如果没有,什么都不做
  3. 如果SD卡可用,请告诉用户我的应用需要读取SD卡的权限,并要求用户通过存储访问框架选择SD卡根目录
  4. 我想为usb棒做同样的事情,但我知道该怎么做(有一个广播接收器可以在添加usb棒时收到通知,我可以检查是否已经连接了)

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    //Ask for the permission

    File externalRoot = Environment.getExternalStorageDirectory(); //gives the root directory of External storage
}

修改

转到.android \ avd \“avd_name”.avd文件夹,然后打开config.ini;确保你有,

hw.sdCard=yes
sdcard.size=100M
sdcard.path=[Path to ".android" directory]/.android/avd/Nexus_5X_API_23.avd/sdcard.img

答案 1 :(得分:0)

这是我到现在为止所做的事情:

File root = Environment.getExternalStorageDirectory();
DocumentFile sdCardRoot = null;

File[] fs = context.getExternalFilesDirs(null);
// at index 0 you have the internal storage and at index 1 the real external...
if (fs != null && fs.length >= 2)
{
    String mainPath = fs[0].getAbsolutePath();
    String subPath = mainPath.replace(root.getFolder().getAbsolutePath(), "");
    String pathSDCard = fs[1].getAbsolutePath().replace(subPath, "");
    String relTreePath = pathSDCard.substring(1).replace("storage", "tree") + "%3A";
    // this string is defined com.android.externalstorage.ExternalStorageProvider... but seems to not be accessable in code...
    Uri treeUri = Uri.withAppendedPath(Uri.parse("content://com.android.externalstorage.documents"), relTreePath);
    sdCardRoot = DocumentFile.fromTreeUri(context, treeUri);
}

// now you have the internal storage root in "root" - this path is directly readable via the `File` class
// and the sd card's root is in sdCardRoot and can be managed via the `DocumentFile` class...