Introducing MediaPicker
With the latest release of the Xamarin Mobile API Preview, in addition to improving the Contacts APIs, we added a new API: MediaPicker. The MediaPicker API provides a common API on iOS, Android, and Windows Phone for taking photos and videos, or selecting them from the media gallery.
It’s a very simple API to use. For example, the following Android code opens the native Android photo browser, allows the user to pick a photo, and then shows that photo in an ImageView:
ImageView image = FindViewById<ImageView> (Resource.Id.image);
var picker = new MediaPicker (this);
picker.PickPhotoAsync()
.ContinueWith (t =>
{
if (t.IsCanceled || t.IsFaulted) // user canceled or error
return;
Bitmap b = BitmapFactory.DecodeFile (t.Result.Path);
RunOnUiThread (() => image.SetImageBitmap (b));
});
The beauty of this API is that the PickPhotoAsync method is available on all three platforms, and works the same way everywhere, though of course the media picker UI looks different on each platform:
Additionally, we have included programmatic feature detection to allow you to determine at runtime what media types are supported via the MediaPicker.PhotosSupported and MediaPicker.VideosSupported Properties. This is especially important for Windows Phone 7, which doesn’t support video in their gallery picker.
Taking Photos or Video
In addition to MediaPicker, we’ve also made it simpler to get access to media file names by allowing you to specify their directory and file name; if you don’t specify a directory, the API will let you know the location to which they were saved.
Furthermore, the API allows you to specify which camera to use, the quality of the video to take, and more, through hint options. You can even query the API to determine what cameras are available:
if (!picker.IsCameraAvailable)
return;
VideoView videoView = FindViewById<VideoView> (Resource.Id.video);
picker.TakeVideoAsync (new StoreVideoOptions
{
Directory = "Xamovies",
DefaultCamera = CameraDevice.Front,
DesiredLength = TimeSpan.FromMinutes (5)
})
.ContinueWith (t =>
{
if (t.IsCanceled || t.IsFaulted) // user canceled or error
return;
videoView.SetVideoPath (t.Result.Path);
});
Fully C# TPL Compatible
And the best part of all this is that the APIs are all asynchronous and built on the C# Task Parallelism Library. This allows you to use the Task.ContinueWith method so that the UI Thread isn’t blocked, and reports user cancellation via IsCanceled and error conditions via the IsFaulted and/or Exception properties.
So download the preview and give it a whirl today!
What’s next?
If you want to influence what cross-platform APIs we create next, feel free to check out our Xamarin Mobile API UserVoice page, where you can vote on features or submit your own ideas.










