private static async Task CreatePhotoAlbumScoped(string albumName)
{
try
{
var contentResolver = Application.Context.ContentResolver;
// We create a directory by inserting a placeholder file
var contentValues = new ContentValues();
contentValues.Put(MediaStore.Images.Media.InterfaceConsts.DisplayName, ".nomedia");
contentValues.Put(MediaStore.Images.Media.InterfaceConsts.MimeType, "image/png");
contentValues.Put(MediaStore.Images.Media.InterfaceConsts.RelativePath, $"DCIM/{albumName}/");
contentValues.Put(MediaStore.Images.Media.InterfaceConsts.IsPending, 1);
var uri = contentResolver?.Insert(MediaStore.Images.Media.ExternalContentUri, contentValues);
if (uri != null)
{
// We write the .nomedia file to create the directory
using var outputStream = contentResolver?.OpenOutputStream(uri);
if (outputStream != null)
{
// Empty file to create the directory
await outputStream.FlushAsync();
}
// Remove the pending flag
contentValues.Clear();
contentValues.Put(MediaStore.Images.Media.InterfaceConsts.IsPending, 0);
contentResolver?.Update(uri, contentValues, null, null);
return true;
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error creating scoped album: {ex.Message}");
}
return false;
}
< /code>
Затем я вставил в него изображения, как это: < /p>
public async Task AddPictureAsync(User user, string pictureName, byte[] pictureData)
{
bool result = true;
if (user == null
|| string.IsNullOrWhiteSpace(pictureName)
|| pictureData == null)
return false;
try
{
// Asking for the photo library authorizations if are not accepted yet.
var photoLibraryAuthorizations = await Permissions.RequestAsync
();
if (photoLibraryAuthorizations != PermissionStatus.Granted)
{
Debug.WriteLine("Permission denied for writing in the gallery");
return result;
}
// Creating the image from the bytes.
Bitmap? bitmap = BitmapFactory.DecodeByteArray(pictureData, 0, pictureData.Length);
if (bitmap == null)
{
Debug.WriteLine("ATTENTION: Bitmap is null during the picture saving in Android.");
return false;
}
// Getting the User photo album.
var contentValues = new ContentValues();
contentValues.Put(MediaStore.IMediaColumns.DisplayName, pictureName);
contentValues.Put(MediaStore.IMediaColumns.MimeType, "image/jpeg");
contentValues.Put(MediaStore.IMediaColumns.RelativePath, "DCIM/" + GetUserPhotoAlbumName(user));
var contentResolver = Application.Context.ContentResolver;
var imageUri = contentResolver?.Insert(MediaStore.Images.Media.ExternalContentUri, contentValues);
using (var outputStream = contentResolver?.OpenOutputStream(imageUri!))
{
await bitmap.CompressAsync(Bitmap.CompressFormat.Jpeg, 100, outputStream);
Debug.WriteLine($"{pictureName} picture correctly added to the {imageUri} photo album.");
}
}
catch (Exception ex)
{
string message = $"Exception in AddPictureAsync (Android): {ex.Message}";
Debug.WriteLine(message);
#if DEBUG
await MainPage.DisplayAlert("User documents directory renaming exception", ex.Message, "OK");
#endif
result = false;
}
return result;
}
< /code>
И все работает нормально, я могу просматривать все изображения, которые я вставил непосредственно из приложения. < /p>
public async Task GetPicturesAsync(User user)
{
if (user == null)
return [];
List pictures = [];
try
{
var photoLibraryAuthorizations = await Permissions.RequestAsync();
if (photoLibraryAuthorizations != PermissionStatus.Granted)
{
Debug.WriteLine("Permission denied for reading the gallery");
return pictures;
}
string albumName = GetUserPhotoAlbumName(user);
using (var cursor = GetPhotoAlbumByName(albumName))
{
if (cursor != null && cursor.MoveToFirst())
{
int idCol = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Id);
int nameCol = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.DisplayName);
int pathCol = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.RelativePath);
int dateCol = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.DateAdded);
int sizeCol = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Size);
do
{
string id = cursor.GetString(idCol);
string name = cursor.GetString(nameCol);
string relativePath = cursor.GetString(pathCol);
long dateAdded = cursor.GetLong(dateCol);
long size = cursor.GetLong(sizeCol);
var contentUri = ContentUris.WithAppendedId(
MediaStore.Images.Media.ExternalContentUri,
cursor.GetLong(idCol));
byte[]? data = null;
try
{
using var stream = Application.Context.ContentResolver?.OpenInputStream(contentUri);
if (stream != null)
{
using var ms = new MemoryStream();
await stream.CopyToAsync(ms);
data = ms.ToArray();
}
}
catch (Exception ex)
{
Debug.WriteLine($"Failed to read bytes for {name}: {ex.Message}");
}
pictures.Add(new CrossFileInfo
{
Id = id,
Name = name,
DirectoryPath = relativePath,
CreationDate = DateTimeOffset.FromUnixTimeSeconds(dateAdded).DateTime,
Storage = size / 1024.0, // KB
Data = data ?? [],
Path = contentUri.ToString()
});
}
while (cursor.MoveToNext());
}
}
}
catch (Exception ex)
{
string message = $"Exception catched in GetPicturesAsync(...): {ex.Message}";
Debug.WriteLine(message);
#if DEBUG
await MainPage.DisplayAlert("User pictures retrieving exception", ex.Message, "Ok");
#endif
}
return pictures;
}
Проблема заключается в том, что если я добавляю изображения в одну и ту же папку с использованием файлового менеджера Android, их не видно MediaStore.
я пробовал различные решения, такие как сканирование с помощью mediaScannerConnection.scanfile () , и они не видят даже с Dieforefiles () . MediaStore (или в целом из приложения) в новых версиях Android?
В моем приложении Maui для Android я создал новую папку, подобную следующему: [code]private static async Task CreatePhotoAlbumScoped(string albumName) { try { var contentResolver = Application.Context.ContentResolver;
// We create a directory by inserting a placeholder file var contentValues = new ContentValues(); contentValues.Put(MediaStore.Images.Media.InterfaceConsts.DisplayName, ".nomedia"); contentValues.Put(MediaStore.Images.Media.InterfaceConsts.MimeType, "image/png"); contentValues.Put(MediaStore.Images.Media.InterfaceConsts.RelativePath, $"DCIM/{albumName}/"); contentValues.Put(MediaStore.Images.Media.InterfaceConsts.IsPending, 1);
var uri = contentResolver?.Insert(MediaStore.Images.Media.ExternalContentUri, contentValues);
if (uri != null) { // We write the .nomedia file to create the directory using var outputStream = contentResolver?.OpenOutputStream(uri); if (outputStream != null) { // Empty file to create the directory await outputStream.FlushAsync(); }
// Remove the pending flag contentValues.Clear(); contentValues.Put(MediaStore.Images.Media.InterfaceConsts.IsPending, 0); contentResolver?.Update(uri, contentValues, null, null);
return false; } < /code> Затем я вставил в него изображения, как это: < /p> public async Task AddPictureAsync(User user, string pictureName, byte[] pictureData) { bool result = true;
try { // Asking for the photo library authorizations if are not accepted yet. var photoLibraryAuthorizations = await Permissions.RequestAsync (); if (photoLibraryAuthorizations != PermissionStatus.Granted) { Debug.WriteLine("Permission denied for writing in the gallery"); return result; }
// Creating the image from the bytes. Bitmap? bitmap = BitmapFactory.DecodeByteArray(pictureData, 0, pictureData.Length); if (bitmap == null) { Debug.WriteLine("ATTENTION: Bitmap is null during the picture saving in Android."); return false; }
// Getting the User photo album. var contentValues = new ContentValues(); contentValues.Put(MediaStore.IMediaColumns.DisplayName, pictureName); contentValues.Put(MediaStore.IMediaColumns.MimeType, "image/jpeg"); contentValues.Put(MediaStore.IMediaColumns.RelativePath, "DCIM/" + GetUserPhotoAlbumName(user));
var contentResolver = Application.Context.ContentResolver; var imageUri = contentResolver?.Insert(MediaStore.Images.Media.ExternalContentUri, contentValues);
using (var outputStream = contentResolver?.OpenOutputStream(imageUri!)) { await bitmap.CompressAsync(Bitmap.CompressFormat.Jpeg, 100, outputStream); Debug.WriteLine($"{pictureName} picture correctly added to the {imageUri} photo album."); } } catch (Exception ex) { string message = $"Exception in AddPictureAsync (Android): {ex.Message}"; Debug.WriteLine(message);
return result; } < /code> И все работает нормально, я могу просматривать все изображения, которые я вставил непосредственно из приложения. < /p> public async Task GetPicturesAsync(User user) { if (user == null) return [];
List pictures = [];
try { var photoLibraryAuthorizations = await Permissions.RequestAsync(); if (photoLibraryAuthorizations != PermissionStatus.Granted) { Debug.WriteLine("Permission denied for reading the gallery"); return pictures; }
string albumName = GetUserPhotoAlbumName(user); using (var cursor = GetPhotoAlbumByName(albumName)) { if (cursor != null && cursor.MoveToFirst()) { int idCol = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Id); int nameCol = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.DisplayName); int pathCol = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.RelativePath); int dateCol = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.DateAdded); int sizeCol = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Size);
do { string id = cursor.GetString(idCol); string name = cursor.GetString(nameCol); string relativePath = cursor.GetString(pathCol); long dateAdded = cursor.GetLong(dateCol); long size = cursor.GetLong(sizeCol);
var contentUri = ContentUris.WithAppendedId( MediaStore.Images.Media.ExternalContentUri, cursor.GetLong(idCol));
byte[]? data = null; try { using var stream = Application.Context.ContentResolver?.OpenInputStream(contentUri); if (stream != null) { using var ms = new MemoryStream(); await stream.CopyToAsync(ms); data = ms.ToArray(); } } catch (Exception ex) { Debug.WriteLine($"Failed to read bytes for {name}: {ex.Message}"); }
return pictures; } [/code] Проблема заключается в том, что если я добавляю изображения в одну и ту же папку с использованием файлового менеджера Android, их не видно MediaStore. я пробовал различные решения, такие как сканирование с помощью mediaScannerConnection.scanfile () , и они не видят даже с Dieforefiles () . MediaStore (или в целом из приложения) в новых версиях Android?