android - 如何检测Android上的哪个存储空间,其中存在图像
问题描述
我正在构建类似图片库应用程序的东西。但是当我使用下面的代码在 Android 设备上检索图像时,我似乎不知道图像是否存在于设备的主要外部存储(内部存储器)或辅助外部存储(SD 卡)中。我将如何区分这两者?
我的代码如下
// root_extra was gotten from the starter of this activity. It can either be MediaStore.Images.Media.EXTERNAL_CONTENT_URI or MediaStore.Images.Media.INTERNAL_CONTENT_URI based on whichever storage location user wants to access by clicking either of two buttons available in the starter activity (Phone storage and SD card)
String root_extra = getIntent().getStringExtra(STORAGE_ACCESS_ROOT);
Uri storageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
if (root_extra != null) {
storageUri = root_extra.equals(EXTERNAL) ? MediaStore.Images.Media.EXTERNAL_CONTENT_URI
: MediaStore.Images.Media.INTERNAL_CONTENT_URI;
}
String[] projection = {
MediaStore.Images.Media._ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.SIZE,
MediaStore.Images.Media.DISPLAY_NAME};
Cursor imgCursor = getApplicationContext()
.getContentResolver()
.query(storageUri, projection, null, null, null);
int bucketId = imgCursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int imgSize = imgCursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE);
int name = imgCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME);
int bucketName
= imgCursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
List<String> dirName = new ArrayList<>();
while (imgCursor.moveToNext()) {
long id = imgCursor.getLong(bucketId);
int size = imgCursor.getInt(imgSize);
String fileName = imgCursor.getString(name);
String folderName = imgCursor.getString(bucketName);
Uri contentUri
= ContentUris.withAppendedId(storageUri, id);
Image currentImage = new Image(contentUri, size, fileName, folderName);
int directoryIndex = linearSearch(dirName, folderName);
// if search result (directoryIndex) passes this test, then it means that there is
// no such directory in list of directory names
if (directoryIndex < 0) {
imageDirectoryList.add(new ArrayList<>());
dirName.add(folderName);
directoryIndex = linearSearch(dirName, folderName);
if (directoryIndex >= 0)
imageDirectoryList.get(directoryIndex).add(currentImage);
} else {
imageDirectoryList.get(directoryIndex).add(currentImage);
}
}
imgCursor.close();
runOnUiThread(() -> {
imageAdapter.notifyDataSetChanged();
doViewUpdate();
});
我MediaStore.Images.Media.INTERNAL_CONTENT_URI
用来访问主外部存储(或我称之为内部存储器),但它不起作用。
解决方案
推荐阅读
- python - 带有 python 的 Onedrive API:路径和上传
- c# - 如何将参数传递给发布 URL C#
- python - 从文本文件中提取 IP 地址并将其用作 Python 中的输入
- qt - RCC:“resource.qrc”中的错误:找不到文件“*.png”
- jar - JBoss 无法加载部署但应用程序正在运行
- sql - hql 查询以检索具有最大日期值的数据
- regex - 从 Ansible 中的 stdout_lines 提取数据
- r - 使用 grepl 在 R 中搜索和更改数据
- sql - 每个商店的前 20 个 SKU 计数
- javascript - 表单验证 ReactJs 中的逻辑问题