Skip to content

Instantly share code, notes, and snippets.

@wislon
Created November 6, 2014 03:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wislon/9fabd1cf250bbf96062a to your computer and use it in GitHub Desktop.
Save wislon/9fabd1cf250bbf96062a to your computer and use it in GitHub Desktop.
Xamarin: Quickly add or remove an item from Android device's gallery
using Android.Content;
using Android.Media;
using Android.Provider;
using Android.Util;
using Uri = Android.Net.Uri;
namespace Classes.Helpers
{
/// <summary>
/// Helper class to help sync your media with the device's gallery (so the videos
/// the app creates appear immediately). The gallery is terrible at realising
/// files have been added or removed, on its own.
/// </summary>
public static class MediaGalleryHelper
{
private const string TAG = "App"
private static readonly Uri _rootUri;
private static readonly ContentResolver _contentResolver;
const string MEDIA_QUERY_STRING = MediaStore.MediaColumns.Data + "=?";
static MediaGalleryHelper()
{
// note it's always the ExternalContentUri, we have no control over where MediaScanner.Scan puts the references,
// they always end up here. InternalContentUri appears to be used for system files only.
_rootUri = MediaStore.Video.Media.ExternalContentUri;
_contentResolver = Android.App.Application.Context.ContentResolver;
}
/// <summary>
/// Will add file to media gallery on the device, make sure the file name is fully qualified.
/// It leaves it up to the device to determine the mime type. Note that this will always end up
/// in the MediaStore's 'ExternalContentUri' section, regardless of where the file is actually
/// located (e.g. internal drive or removable SD card). This is done entirely by the device,
/// we have no control of this.
/// </summary>
/// <param name="fileName">Fully qualified file name to add to the gallery. </param>
public static void AddFileToGallery(string fileName)
{
Log.Debug(TAG, "Adding {0} to the gallery", fileName);
// note that you can pass an array of FQ file names too, but those files must exist or you
// end up with empty gray placeholders in the gallery.
MediaScannerConnection.ScanFile(Android.App.Application.Context, new string[] { fileName }, null, null);
}
/// <summary>
/// Will delete a file from the media gallery on the device. Ensure the file name is fully qualified.
/// Note that if you call this method and the file still exists, IT WILL BE DELETED FROM THE DEVICE.
/// </summary>
/// <param name="fileName">Fully qualified file name to add to the gallery. </param>
public static void RemoveFileFromGallery(string fileName)
{
Log.Debug(TAG, "Deleting {0} from the gallery", fileName);
_contentResolver.Delete(_rootUri, MEDIA_QUERY_STRING, new string[] { fileName });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment