Android Q Api 29 - 如何从“存储访问框架(Storage Access Framework)”中获取存储(SD卡)的大小(总大小或可用大小)
创始人
2024-08-15 02:00:19
0

要从存储访问框架(Storage Access Framework)中获取存储(SD卡)的大小(总大小或可用大小),您可以使用以下代码示例:

首先,添加以下权限到AndroidManifest.xml文件中:


然后,使用以下代码获取存储的大小:

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getStorageSize();
    }

    @SuppressLint("NewApi")
    private void getStorageSize() {
        Uri uri = MediaStore.Files.getContentUri("external");

        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query(uri, null, null, null, null, null);

        long totalSize = 0;
        long availableSize = 0;

        if (cursor != null) {
            while (cursor.moveToNext()) {
                String fileSize = cursor.getString(cursor.getColumnIndex(DocumentsContract.Document.COLUMN_SIZE));
                totalSize += Long.parseLong(fileSize);
            }
            cursor.close();
        }

        Log.d(TAG, "Total storage size: " + totalSize);

        StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
        long blockSize = stat.getBlockSizeLong();
        long availableBlocks = stat.getAvailableBlocksLong();
        availableSize = availableBlocks * blockSize;

        Log.d(TAG, "Available storage size: " + availableSize);
    }
}

上述代码使用MediaStore.Files.getContentUri("external")获取存储的内容URI,并通过查询DocumentsContract.Document.COLUMN_SIZE来获取每个文件的大小,然后累加得到存储的总大小。

另外,代码还使用Environment.getExternalStorageDirectory().getPath()获取外部存储目录的路径,并使用StatFs类来获取可用的存储大小。

请注意,这些代码需要在Android Q (API 29)及更高版本上运行,并且需要在运行时请求存储权限。

相关内容

热门资讯

详情透视!wepoker的辅助... 详情透视!wepoker的辅助器,微乐小程序辅助器脚本,方式教程(有挂猫腻)-哔哩哔哩1、首先打开w...
详细透视!fishpoker透... 详细透视!fishpoker透视底牌!本来有辅助工具(确实有挂)-哔哩哔哩1、fishpoker透视...
专业透视!竞技联盟破解版最新版... 专业透视!竞技联盟破解版最新版,微信小程序微乐挂如何获取,法门教程(竟然有挂)-哔哩哔哩1、起透看视...
分享透视!约局吧能不能开挂!切... 分享透视!约局吧能不能开挂!切实真的有辅助攻略(确实有挂)-哔哩哔哩1、超多福利:超高返利,海量正版...
分享透视!hhpoker是正规... 分享透视!hhpoker是正规的吗,微乐自建房辅助神器怎么安装,资料教程(的确有挂)-哔哩哔哩1、下...
教你透视!pokemmo内置修... 教你透视!pokemmo内置修改器!一贯是有辅助脚本(发现有挂)-哔哩哔哩1、pokemmo内置修改...
揭幕透视!哈糖大菠萝免费辅助器... 揭幕透视!哈糖大菠萝免费辅助器,微乐小程序卡五星脚本,积累教程(有挂解惑)-哔哩哔哩1、完成哈糖大菠...
详细透视!xpoker辅助助手... 详细透视!xpoker辅助助手!本来一直总是有辅助教程(有挂细节)-哔哩哔哩1、点击下载安装,xpo...
关于透视!约局吧怎么看有没有挂... 关于透视!约局吧怎么看有没有挂,微信小程序游戏充值破解,方式教程(有挂秘诀)-哔哩哔哩在进入约局吧怎...
详情透视!红龙poker作必弊... 详情透视!红龙poker作必弊指令!原来是真的有辅助教程(有人有挂)-哔哩哔哩1.红龙poker作必...