string CreateFileAndGetFileNameFromUri(Android.Net.Uri Uri) { string FileName = ""; if (Uri.ToString().StartsWith("content://")) { using (var cursor = ContentResolver.Query(Uri, null, null, null, null)) { cursor.MoveToFirst(); FileName = cursor.GetString(cursor.GetColumnIndex(OpenableColumns.DisplayName)); } } else { FileName = new Java.IO.File(Uri.ToString()).Name; } //將檔案寫進 App 內 using (Stream input = ContentResolver.OpenInputStream(Uri)) { using (var FileStream = File.Create(FilesDir.AbsolutePath + "/" + FileName)) { input.CopyTo(FileStream); } } return(FileName); }
public override ParcelFileDescriptor OpenFile(Android.Net.Uri uri, String mode) { const string logTag = ClassName + " - openFile"; Log.Verbose(logTag, "Called with uri: '" + uri + "'." + uri.LastPathSegment); if (uri.ToString().StartsWith("content://" + Authority)) { // The desired file name is specified by the last segment of the // path // E.g. // 'content://keepass2android.provider/Test.txt' // Take this and build the path to the file //Protect against path traversal with an uri like content://keepass2android.keepass2android.provider/..%2F..%2Fshared_prefs%2FKP2A.Plugin.keepass2android.plugin.qr.xml if (uri.LastPathSegment.Contains("/")) { throw new Exception("invalid path "); } String fileLocation = Context.CacheDir + File.Separator + AttachmentCacheSubDir + File.Separator + uri.LastPathSegment; // Create & return a ParcelFileDescriptor pointing to the file // Note: I don't care what mode they ask for - they're only getting // read only ParcelFileDescriptor pfd = ParcelFileDescriptor.Open(new File( fileLocation), ParcelFileMode.ReadOnly); return(pfd); } Log.Verbose(logTag, "Unsupported uri: '" + uri + "'."); throw new FileNotFoundException("Unsupported uri: " + uri.ToString()); }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null)) { Android.Net.Uri uri = data.Data; sciezkaPliku.Text = uri.ToString(); sciezka = uri.ToString(); } }
internal static Task <MediaPickedEventArgs> GetMediaFileAsync(Context context, int requestCode, string action, bool isPhoto, ref Uri path, Uri data, bool saveToAlbum) { Task <Tuple <string, string, bool> > pathFuture; string originalPath = null; if (action != Intent.ActionPick) { originalPath = path.Path; // Not all camera apps respect EXTRA_OUTPUT, some will instead // return a content or file uri from data. if (data != null && data.Path != originalPath) { originalPath = data.ToString(); var currentPath = path.Path; var originalFilename = Path.GetFileName(currentPath); pathFuture = TryMoveFileAsync(context, data, path, isPhoto, false).ContinueWith(t => new Tuple <string, string, bool>(t.Result ? currentPath : null, t.Result ? originalFilename : null, false)); } else { pathFuture = TaskFromResult(new Tuple <string, string, bool>(path.Path, Path.GetFileName(path.Path), false)); } } else if (data != null) { originalPath = data.ToString(); path = data; pathFuture = GetFileForUriAsync(context, path, isPhoto, false); } else { pathFuture = TaskFromResult <Tuple <string, string, bool> >(null); } return(pathFuture.ContinueWith(t => { var resultPath = t?.Result?.Item1; var originalFilename = t?.Result?.Item2; var aPath = originalPath; if (resultPath != null && File.Exists(resultPath)) { var mf = new MediaFile(resultPath, () => { return File.OpenRead(resultPath); }, albumPath: aPath, originalFilename: originalFilename); return new MediaPickedEventArgs(requestCode, false, mf); } else { return new MediaPickedEventArgs(requestCode, new MediaFileNotFoundException(originalPath)); } })); }
/// <summary> /// Gets the media file asynchronous. /// </summary> /// <param name="context">The context.</param> /// <param name="requestCode">The request code.</param> /// <param name="action">The action.</param> /// <param name="isPhoto">if set to <c>true</c> [is photo].</param> /// <param name="path">The path.</param> /// <param name="data">The data.</param> /// <returns>Task<MediaPickedEventArgs>.</returns> internal static Task <MediaPickedEventArgs> GetMediaFileAsync(Context context, int requestCode, string action, bool isPhoto, ref Uri path, Uri data) { Task <Tuple <string, bool> > pathFuture; Action <bool> dispose = null; string originalPath = null; if (action != Intent.ActionPick) { originalPath = path.Path; // Not all camera apps respect EXTRA_OUTPUT, some will instead // return a content or file uri from data. if (data != null && data.Path != originalPath) { originalPath = data.ToString(); var currentPath = path.Path; pathFuture = TryMoveFileAsync(context, data, path, isPhoto).ContinueWith(t => new Tuple <string, bool>(t.Result ? currentPath : null, false)); } else { pathFuture = TaskUtils.TaskFromResult(new Tuple <string, bool>(path.Path, false)); } } else if (data != null) { originalPath = data.ToString(); path = data; pathFuture = GetFileForUriAsync(context, path, isPhoto); } else { pathFuture = TaskUtils.TaskFromResult <Tuple <string, bool> >(null); } return(pathFuture.ContinueWith(t => { string resultPath = t.Result.Item1; if (resultPath != null && File.Exists(t.Result.Item1)) { if (t.Result.Item2) { dispose = d => File.Delete(resultPath); } var mf = new MediaFile(resultPath, () => File.OpenRead(t.Result.Item1), dispose); return new MediaPickedEventArgs(requestCode, false, mf); } return new MediaPickedEventArgs(requestCode, new MediaFileNotFoundException(originalPath)); })); }
public async Task <string> getRealPathFromURI(Context context, Android.Net.Uri contentURI) { try { var fixedUri = FixUri(contentURI.Path); if (fixedUri != null) { contentURI = fixedUri; } if (contentURI.Scheme == "file") { var _filepath = new System.Uri(contentURI.ToString()).LocalPath; //mid.ShowImageAndroid(_filepath); return(_filepath); } else if (contentURI.Scheme == "content") { ICursor cursor = ContentResolver.Query(contentURI, null, null, null, null); try { string contentPath = null; cursor.MoveToFirst(); string[] projection = new[] { MediaStore.Images.Media.InterfaceConsts.Data }; String document_id = cursor.GetString(0); document_id = document_id.Substring(document_id.LastIndexOf(":") + 1); cursor.Close(); cursor = ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, null, MediaStore.Images.Media.InterfaceConsts.Id + " = ? ", new String[] { document_id }, null); cursor.MoveToFirst(); contentPath = cursor.GetString(cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Data)); cursor.Close(); return(contentPath); } catch (Exception ex) { var msg = ex.Message; return(null); } finally { if (cursor != null) { cursor.Close(); cursor.Dispose(); } } } else { return(null); } } catch (Exception ex) { var msg = ex.Message; return(null); } }
private void SaveOutput(Bitmap croppedImage) { if (_saveUri != null) { try { using (var outputStream = ContentResolver.OpenOutputStream(_saveUri)) { if (outputStream != null) { croppedImage.Compress(_outputFormat, 75, outputStream); } } } catch (Exception ex) { Log.Error(GetType().Name, ex.Message); } var extras = new Bundle(); SetResult(Result.Ok, new Intent(_saveUri.ToString()) .PutExtras(extras)); } else { Log.Error(GetType().Name, "not defined image url"); } croppedImage.Recycle(); Finish(); }
private void UpdateUI(FirebaseUser user) { // Signed in or Signed out if (user != null) { FindViewById(Resource.Id.layout_signin).Visibility = ViewStates.Gone; FindViewById(Resource.Id.layout_storage).Visibility = ViewStates.Visible; } else { FindViewById(Resource.Id.layout_signin).Visibility = ViewStates.Visible; FindViewById(Resource.Id.layout_storage).Visibility = ViewStates.Gone; } // Download URL and Download button if (mDownloadUrl != null) { ((TextView)FindViewById(Resource.Id.picture_download_uri)) .Text = mDownloadUrl.ToString(); FindViewById(Resource.Id.layout_download).Visibility = ViewStates.Visible; } else { ((TextView)FindViewById(Resource.Id.picture_download_uri)) .Text = string.Empty; FindViewById(Resource.Id.layout_download).Visibility = ViewStates.Gone; } }
public void OpenUri(Activity activity, Android.Net.Uri uri) { var intent = new Intent(activity, typeof(WebviewActivity)); intent.PutExtra(WebviewActivity.EXTRA_URL, uri.ToString()); activity.StartActivity(intent); }
void ExecuteCallbackUri(Android.Net.Uri callbackUri) { var navigationPage = (Xamarin.Forms.NavigationPage)Xamarin.Forms.Application.Current.MainPage; navigationPage.Pushed += HandlePushed; async void HandlePushed(object sender, Xamarin.Forms.NavigationEventArgs e) { if (e.Page is SettingsPage) { navigationPage.Pushed -= HandlePushed; try { using var scope = ContainerService.Container.BeginLifetimeScope(); var gitHubAuthenticationService = scope.Resolve <GitHubAuthenticationService>(); await gitHubAuthenticationService.AuthorizeSession(new Uri(callbackUri.ToString())).ConfigureAwait(false); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } } } }
protected override string RunInBackground(params string[] paths) { string filePath = null !; try { //This bellow is just a temporary solution to test that method call works var b = bool.Parse(paths[0]); if (b) { filePath = SiliCompressor.With(MContext).CompressVideo(paths[1], paths[2]); } else { Android.Net.Uri videoContentUri = Android.Net.Uri.Parse(paths[1]); // Example using the bitrate and video size parameters = >> filePath = SiliCompressor.with(mContext).compressVideo(videoContentUri, paths[2], 1280,720,1500000);*/ filePath = SiliCompressor.With(MContext).CompressVideo(videoContentUri?.ToString(), paths[2]); } } catch (URISyntaxException e) { Methods.DisplayReportResultTrack(e); } catch (Exception e) { Methods.DisplayReportResultTrack(e); } return(filePath); }
/// <summary> /// Play the currently selected song /// </summary> public override void Play() { base.Play(); // Prevent this from being called again until it has been processed if (isPreparing == false) { // Get the source path for the current song string filename = GetSongResource(true); if (filename.Length > 0) { // Set uri Android.Net.Uri trackUri = Android.Net.Uri.Parse(filename); try { localPlayer.Reset(); localPlayer.SetDataSource(trackUri.ToString()); isPreparing = true; localPlayer.PrepareAsync(); } catch (Exception error) { Logger.Error(string.Format("Error setting data source for : {0} : {1}", filename, error.Message)); } } } }
string GetFileName(Context ctx, Android.Net.Uri uri) { string [] projection = { MediaStore.MediaColumns.DisplayName }; var cr = ctx.ContentResolver; var name = ""; var metaCursor = cr.Query(uri, projection, null, null, null); if (metaCursor != null) { try { if (metaCursor.MoveToFirst()) { name = metaCursor.GetString(0); } } finally { metaCursor.Close(); } } if (!string.IsNullOrWhiteSpace(name)) { return(name); } else { return(System.IO.Path.GetFileName(WebUtility.UrlDecode(uri.ToString()))); } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Android.Net.Uri uri_android = Intent.Data; // Convert iOS NSUrl to C#/netxf/BCL System.Uri - common API Uri uri_netfx = new Uri(uri_android.ToString()); // Send the URI to the Authenticator for continuation if (uri_netfx.Authority == "oauth.yandex.ru") { Clouds.YD.Auth?.OnPageLoading(uri_netfx); } else { Clouds.GD.Auth?.OnPageLoading(uri_netfx); } var intent = new Intent(this, typeof(MainActivity)); intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop); StartActivity(intent); Finish(); }
private void SaveOutput(Bitmap croppedImage) { if (saveUri != null) { try { using (var outputStream = ContentResolver.OpenOutputStream(saveUri)) { if (outputStream != null) { croppedImage.Compress(outputFormat, 75, outputStream); } } } catch (Exception ex) { Log.Error(this.GetType().Name, ex.Message); } Bundle extras = new Bundle(); SetResult(Result.Ok, new Intent(saveUri.ToString()) .PutExtras(extras)); CropImageServiceAndroid.SetResult(new CropResult(true) { FilePath = saveUri.Path, Message = "Image cropped successfully" }); } else { Log.Error(this.GetType().Name, "not defined image url"); } croppedImage.Recycle(); Finish(); }
private void GetVideoFrames(int viewWidth) { MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever(); try { mediaMetadataRetriever.SetDataSource(mVideoUri.ToString(), new Dictionary <string, string>()); // Retrieve media data long videoLengthInMs = Convert.ToInt64(mediaMetadataRetriever.ExtractMetadata(MetadataKey.Duration)) * 1000; // Set thumbnail properties (Thumbs are squares) int thumbWidth = mHeightView; int thumbHeight = mHeightView; int numThumbs = (int)Math.Ceiling(((float)viewWidth) / thumbWidth); long interval = videoLengthInMs / numThumbs; for (int i = 0; i < numThumbs; ++i) { Bitmap bitmap = mediaMetadataRetriever.GetFrameAtTime(i * interval, Android.Media.Option.ClosestSync); bitmap = Bitmap.CreateScaledBitmap(bitmap, thumbWidth, thumbHeight, false); mBitmapList.Add(bitmap); } } catch (Exception ex) { Log.Error("Error", ex.ToString()); } finally { mediaMetadataRetriever.Release(); } }
public void OnCompleted(JSONObject p0, GraphResponse p1) { FacebookResponseK fbResponse = JsonConvert.DeserializeObject <FacebookResponseK>(p1.RawResponse); profile = Profile.CurrentProfile; if (profile != null) { var buttonFB = view.FindViewById <Button>(Resource.Id.buttonFB); buttonFB.Enabled = false; buttonFB.SetBackgroundColor(Xamarin.Forms.Color.Gray.ToAndroid()); profilePictureView.ProfileId = profile.Id; Android.Net.Uri profilePic = profile.GetProfilePictureUri(220, 220); fbPictureUrl = profilePic.ToString(); //chito.do not force user to must have an email viewModel.FacebookEmail = fbResponse.email ?? ""; viewModel.FacebookFirstName = firstname ?? fbResponse.first_name; viewModel.FacebookLastName = lastname ?? fbResponse.last_name; viewModel.FacebookPhoto = fbPictureUrl; viewModel.FacebookBirthday = fbResponse.birthday; viewModel.FacebookGender = fbResponse.gender; viewModel.FacebookId = fbResponse.id ?? "0"; viewModel.FacebookLink = fbResponse.link; viewModel.SaveFacebookProfileAsync(); } }
public async void Download_Click() { //var destination = Path.Combine( // System.Environment.GetFolderPath( // System.Environment.SpecialFolder.ApplicationData), // "music.mp3"); //await new WebClient().DownloadFileTaskAsync( // new System.Uri(path), // destination); Android.App.DownloadManager dm; uri = Android.Net.Uri.FromFile(new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory + "/Download/xyz.mp4")); string lastSegment = uri.PathSegments.Last(); string struri = uri.ToString(); if (System.IO.File.Exists(struri)) { // string currenturi = uri + lastSegment; return; } else { dm = Android.App.DownloadManager.FromContext(Activity); Android.App.DownloadManager.Request request = new Android.App.DownloadManager.Request(Android.Net.Uri.Parse(path)); request.SetTitle("Task App").SetDescription("Task Audio"); request.SetVisibleInDownloadsUi(true); request.SetNotificationVisibility(Android.App.DownloadVisibility.VisibleNotifyCompleted); request.SetDestinationUri(uri); var c = dm.Enqueue(request); } }
public static string GetFileName(Context context, Android.Net.Uri uri) { var mimeType = context.ContentResolver.GetType(uri); string filename = null; if (mimeType == null) { Java.IO.File file = new Java.IO.File(uri.ToString()); filename = file.Name; } else { ICursor cursor = null; try { cursor = context.ContentResolver.Query(uri, null, null, null); if (cursor != null && cursor.MoveToFirst()) { int nameIndex = cursor.GetColumnIndex("_display_name"); if (nameIndex > -1) { filename = cursor.GetString(nameIndex); } } } finally { if (cursor != null) { cursor.Close(); } } } return(filename); }
public static void SetCloseSoundPath(Android.Net.Uri path) { Log.Debug(TAG, "SetCloseSoundPath"); using (var writer = File.CreateText(CLOSE_SOUND_RECORD_PATH)) { writer.WriteLine(path.ToString()); } }
public List <object> GetOfflineStreamKeys(android.Net.Uri uri) { if (!trackedDownloadStates.ContainsKey(uri.ToString())) { return(new List <object>()); } DownloadAction action = trackedDownloadStates[uri.ToString()]; if (action is SegmentDownloadAction) { List <object> objs = new List <object>(((SegmentDownloadAction)action).Keys.ToArray()); return(objs); } return(new List <object>()); }
public static void DirectorySelected(Uri directory) { var contentResolver = MainActivity.Instance.ContentResolver; contentResolver.TakePersistableUriPermission(directory, ActivityFlags.GrantReadUriPermission | ActivityFlags.GrantWriteUriPermission); _completionSource.SetResult(directory.ToString()); }
public override void SetImageURI(Uri uri) { base.SetImageURI(uri); var stream = Application.Context.ContentResolver.OpenInputStream(uri); var drawable = Drawable.CreateFromStream(stream, uri.ToString()); _mBitmap = GetBitmapFromDrawable(drawable); Setup(); }
public static void OnVideoResult(Uri result, bool deleteFile = false) { var loader = ProgressDialog.Show(DroidFactory.MainActivity, string.Empty, iApp.Factory.GetResourceString("SaveVideo") ?? "Saving video...", true); iApp.Thread.QueueWorker(o => { string extension = null; var uriString = result?.ToString().ToLowerInvariant() ?? string.Empty; if (uriString.StartsWith("content:")) { extension = MimeTypeMap.Singleton.GetExtensionFromMimeType(DroidFactory.MainActivity.ContentResolver.GetType(result)); } else if (uriString.StartsWith("file://")) { extension = uriString.Substring(uriString.LastIndexOf('.') + 1); } if (extension == null) { Toast.MakeText(DroidFactory.MainActivity, iApp.Factory.GetResourceString("InvalidFile") ?? "Invalid file", ToastLength.Short).Show(); return; } var mime = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); if (mime == null || !mime.StartsWith("video")) { Toast.MakeText(DroidFactory.MainActivity, iApp.Factory.GetResourceString("InvalidFile") ?? "Invalid file", ToastLength.Short).Show(); return; } string videoId = null; try { videoId = DroidFactory.Instance.StoreImage(result, extension); if (deleteFile) { DroidFactory.MainActivity.ContentResolver.Delete(result, null, null); } } catch (IOException e) { iApp.Log.Error(e); Toast.MakeText(DroidFactory.MainActivity, iApp.Factory.GetResourceString("VideoError") ?? "There was a problem saving the video. Please check your disk usage.", ToastLength.Long).Show(); } DroidFactory.MainActivity.RunOnUiThread(loader.Dismiss); if (_callback == null) { return; } DroidFactory.Navigate(new Link(_callback, new Dictionary <string, string> { { CallbackParam, videoId } })); _callback = null; }); }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (resultCode == Result.Ok) { Android.Net.Uri ring = (Android.Net.Uri)data.GetParcelableExtra(RingtoneManager.ExtraRingtonePickedUri); this.ViewModel.SetRingUri.Execute(ring.ToString()).Subscribe(); } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Android.Net.Uri uri_android = Intent.Data; Uri uri_netfx = new Uri(uri_android.ToString()); LoginHelper.s_GoogleAuthenticator?.OnPageLoading(uri_netfx); Finish(); }
public XmlDocument LoadXmlFromContentUri(Android.Net.Uri uri) { Logger.Debug(() => $"FileSystemHelper:LoadXmlFromContentUri = {uri.ToString()}"); ContentResolver resolver = ApplicationContext.ContentResolver; var stream = resolver.OpenInputStream(uri); var xml = new XmlDocument(); xml.Load(stream); return(xml); }
protected void custom_tabs_activit_manager_CustomTabsServiceConnected ( Android.Content.ComponentName name, CustomTabsClient client ) { custom_tabs_intent_builder = new CustomTabsIntent.Builder(custom_tabs_activity_manager.Session); custom_tabs_intent_builder.EnableUrlBarHiding(); if (CustomTabsConfiguration.IsWarmUpUsed) { System.Diagnostics.Debug.WriteLine("CustomTabsActivityManager.WarmUp()"); client.Warmup(0); //custom_tabs_activity_manager.Warmup(); } if (CustomTabsConfiguration.IsPrefetchUsed) { System.Diagnostics.Debug.WriteLine("CustomTabsActivityManager PREFETCH"); custom_tabs_activity_manager.MayLaunchUrl(uri.ToString(), null, null); } if (CustomTabsConfiguration.AreAnimationsUsed) { custom_tabs_intent_builder.SetStartAnimations ( activity, Xamarin.Auth.Resource.Animation.slide_in_right, Xamarin.Auth.Resource.Animation.slide_out_left ); custom_tabs_intent_builder.SetExitAnimations ( activity, global::Android.Resource.Animation.SlideInLeft, global::Android.Resource.Animation.SlideOutRight ); } custom_tabs_activity_manager.LaunchUrl(uri.ToString(), custom_tabs_intent_builder.Build()); return; }
/// <summary> /// 初始化数据 /// </summary> private void InitData() { // 第一帧图片 Bitmap bitmap = null; // 获取视频第一帧 MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { Android.Net.Uri uri = Android.Net.Uri.Parse(url); if (Build.VERSION.SdkInt >= Build.VERSION_CODES.IceCreamSandwich) { retriever.SetDataSource(uri.ToString(), new Dictionary <string, string>()); } else { retriever.SetDataSource(uri.ToString()); } // 获取第一帧图片 bitmap = retriever.GetFrameAtTime(0, MediaMetadataRetriever.OptionClosest); imageView_VideoThumbnail.SetImageBitmap(bitmap); progressBar_VideoProgressBar.Visibility = ViewStates.Gone; imageView_VideoPlay.Visibility = ViewStates.Visible; imageView_VideoPause.Visibility = ViewStates.Gone; // 进度条 seekBar_VideoTotal = Convert.ToInt32(retriever.ExtractMetadata((int)MetadataKey.Duration)) / 1000; seekBar_VideoSeekBar.Max = Convert.ToInt32(retriever.ExtractMetadata((int)MetadataKey.Duration)) / 1000; seekBar_VideoSeekBar.Enabled = true; textView_VideoTotalTime.Text = (seekBar_VideoTotal / 60).ToString("00") + " : " + (seekBar_VideoTotal % 60).ToString("00"); retriever.Release(); } catch (Exception) { retriever.Release(); } }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null)) { string userName = user.Username; //Retrieving the current username Android.Net.Uri uri = data.Data; imageViewPic.SetImageURI(uri); image.ImageUri = uri.ToString(); btnUpdate.Enabled = true; //Enabling the update button } }
public HtmlElement(string caption, Uri uri) : base(caption, uri.ToString(), "dialog_labelfieldright") { Url = uri; }
/// <summary> /// Gets the local path. /// </summary> /// <param name="uri">The URI.</param> /// <returns>System.String.</returns> private static string GetLocalPath(Uri uri) { return new System.Uri(uri.ToString()).LocalPath; }
/// <summary> /// Gets the file for URI asynchronous. /// </summary> /// <param name="context">The context.</param> /// <param name="uri">The URI.</param> /// <param name="isPhoto">if set to <c>true</c> [is photo].</param> /// <returns>Task<Tuple<System.String, System.Boolean>>.</returns> internal static Task<Tuple<string, bool>> GetFileForUriAsync(Context context, Uri uri, bool isPhoto) { var tcs = new TaskCompletionSource<Tuple<string, bool>>(); if (uri.Scheme == "file") tcs.SetResult(new Tuple<string, bool>(new System.Uri(uri.ToString()).LocalPath, false)); else if (uri.Scheme == "content") { Task.Factory.StartNew(() => { ICursor cursor = null; try { cursor = context.ContentResolver.Query(uri, null, null, null, null); if (cursor == null || !cursor.MoveToNext()) tcs.SetResult(new Tuple<string, bool>(null, false)); else { int column = cursor.GetColumnIndex(MediaStore.MediaColumns.Data); string contentPath = null; if (column != -1) contentPath = cursor.GetString(column); bool copied = false; // If they don't follow the "rules", try to copy the file locally // if (contentPath == null || !contentPath.StartsWith("file")) // { // copied = true; // Uri outputPath = GetOutputMediaFile(context, "temp", null, isPhoto); // // try // { // using (Stream input = context.ContentResolver.OpenInputStream(uri)) // using (Stream output = File.Create(outputPath.Path)) // input.CopyTo(output); // // contentPath = outputPath.Path; // } // catch (FileNotFoundException) // { // // If there's no data associated with the uri, we don't know // // how to open this. contentPath will be null which will trigger // // MediaFileNotFoundException. // } // } tcs.SetResult(new Tuple<string, bool>(contentPath, copied)); } } finally { if (cursor != null) { cursor.Close(); cursor.Dispose(); } } }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); } else tcs.SetResult(new Tuple<string, bool>(null, false)); return tcs.Task; }
/// <summary> /// Gets the media file asynchronous. /// </summary> /// <param name="context">The context.</param> /// <param name="requestCode">The request code.</param> /// <param name="action">The action.</param> /// <param name="isPhoto">if set to <c>true</c> [is photo].</param> /// <param name="path">The path.</param> /// <param name="data">The data.</param> /// <returns>Task<MediaPickedEventArgs>.</returns> internal static Task<MediaPickedEventArgs> GetMediaFileAsync(Context context, int requestCode, string action, bool isPhoto, ref Uri path, Uri data) { Task<Tuple<string, bool>> pathFuture; Action<bool> dispose = null; string originalPath = null; if (action != Intent.ActionPick) { originalPath = path.Path; // Not all camera apps respect EXTRA_OUTPUT, some will instead // return a content or file uri from data. if (data != null && data.Path != originalPath) { originalPath = data.ToString(); var currentPath = path.Path; pathFuture = TryMoveFileAsync(context, data, path, isPhoto).ContinueWith(t => new Tuple<string, bool>(t.Result ? currentPath : null, false)); } else pathFuture = TaskUtils.TaskFromResult(new Tuple<string, bool>(path.Path, false)); } else if (data != null) { originalPath = data.ToString(); path = data; pathFuture = GetFileForUriAsync(context, path, isPhoto); } else { pathFuture = TaskUtils.TaskFromResult<Tuple<string, bool>>(null); } return pathFuture.ContinueWith(t => { string resultPath = t.Result.Item1; if (resultPath != null && File.Exists(t.Result.Item1)) { if (t.Result.Item2) { dispose = d => File.Delete(resultPath); } var mf = new MediaFile(resultPath, () => File.OpenRead(t.Result.Item1) , dispose); return new MediaPickedEventArgs(requestCode, false, mf); } return new MediaPickedEventArgs(requestCode, new MediaFileNotFoundException(originalPath)); }); }