public static void ShareSong(Context context, long id)
        {
            var projection = new[]
            {
                BaseColumns.Id,
                MediaStore.MediaColumns.Data,
                MediaStore.Audio.AudioColumns.AlbumId
            };

            var selection = $"{projection[0]} IN ({id})";
            var c         = context.ContentResolver.Query(MediaStore.Audio.Media.ExternalContentUri, projection, selection, null, null);

            if (c is null)
            {
                return;
            }
            c.MoveToFirst();
            try
            {
                var share = new Intent(Intent.ActionSend);
                share.SetType("audio/*");
                share.PutExtra(Intent.ExtraStream, Uri.FromFile(new Java.IO.File(c.GetString(1))));
                context.StartActivity(Intent.CreateChooser(share, "Share the song"));
                c.Close();
            }
            catch { }
        }
        internal static AndroidUri GetShareableFileUri(FileBase file)
        {
            Java.IO.File sharedFile;
            if (FileProvider.IsFileInPublicLocation(file.FullPath))
            {
                // we are sharing a file in a "shared/public" location
                sharedFile = new Java.IO.File(file.FullPath);
            }
            else
            {
                var root = FileProvider.GetTemporaryRootDirectory();

                var tmpFile = FileSystem.GetEssentialsTemporaryFile(root, file.FileName);

                System.IO.File.Copy(file.FullPath, tmpFile.CanonicalPath);

                sharedFile = tmpFile;
            }

            // create the uri, if N use file provider
            if (HasApiLevelN)
            {
                return(FileProvider.GetUriForFile(sharedFile));
            }

            // use the shared file path created
            return(AndroidUri.FromFile(sharedFile));
        }
        void ShareCurrentPhoto()
        {
            File externalCacheDir = Activity.ExternalCacheDir;

            if (externalCacheDir == null)
            {
                Toast.MakeText(Activity, "Error writing to USB/external storage.",
                               ToastLength.Short).Show();
                return;
            }

            // Prevent media scanning of the cache directory.
            File noMediaFile = new File(externalCacheDir, ".nomedia");

            try {
                noMediaFile.CreateNewFile();
            } catch (IOException e) {
            }

            // Write the bitmap to temporary storage in the external storage directory (e.g. SD card).
            // We perform the actual disk write operations on a separate thread using the
            // {@link AsyncTask} class, thus avoiding the possibility of stalling the main (UI) thread.

            File tempFile = new File(externalCacheDir, "tempfile.jpg");

            new AsyncTaskImpl(delegate(Java.Lang.Object [] parms) {
                /**
                 * Compress and write the bitmap to disk on a separate thread.
                 * @return TRUE if the write was successful, FALSE otherwise.
                 */
                try {
                    var fo = System.IO.File.OpenWrite(tempFile.AbsolutePath);
                    if (!mBitmap.Compress(Bitmap.CompressFormat.Jpeg, 60, fo))
                    {
                        Toast.MakeText(Activity, "Error writing bitmap data.", ToastLength.Short).Show();
                        return(false);
                    }
                    return(true);
                } catch (FileNotFoundException e) {
                    Toast.MakeText(Activity, "Error writing to USB/external storage.", ToastLength.Short).Show();
                    return(false);
                }
            }, delegate {
                throw new System.NotImplementedException();
            }, delegate(bool result) {
                /**
                 * After doInBackground completes (either successfully or in failure), we invoke an
                 * intent to share the photo. This code is run on the main (UI) thread.
                 */
                if (result != true)
                {
                    return;
                }

                Intent shareIntent = new Intent(Intent.ActionSend);
                shareIntent.PutExtra(Intent.ExtraStream, Uri.FromFile(tempFile));
                shareIntent.SetType("image/jpeg");
                StartActivity(Intent.CreateChooser(shareIntent, "Share photo"));
            }).Execute();
        }
Esempio n. 4
0
        public string RetrivePathForPDF(string name)
        {
            string _path = "";

            _path = Path.Combine(_newPath, name);
            Java.IO.File f = new Java.IO.File(_path);

            Uri uri;

            if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
            {
                uri = Uri.Parse("content://" + _path);
            }
            else
            {
                Java.IO.File file = new Java.IO.File(_path);
                file.SetReadable(true);
                //Android.Net.Uri uri = Android.Net.Uri.Parse("file://" + filePath);
                uri = Uri.FromFile(file);
            }

            var uri1 = FileProvider.GetUriForFile(MainActivity.MainActivityInstance.ApplicationContext, MainActivity.MainActivityInstance.ApplicationContext.PackageName + ".provider", f);

            return(uri1.Path);
        }
        private void UpdateGallery(File file)
        {
            Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
            Uri    contentUri      = Uri.FromFile(file);

            mediaScanIntent.SetData(contentUri);
            Application.Context.SendBroadcast(mediaScanIntent);
        }
Esempio n. 6
0
        private void GalleryAddPhoto()
        {
            Intent MediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
            File   f          = new File(CurrentPhotoPath);
            Uri    contentUri = Uri.FromFile(f);

            MediaScanIntent.SetData(contentUri);
            this.SendBroadcast(MediaScanIntent);
        }
        private void TakeAPicture(object sender, EventArgs e)
        {
            Intent intent = new Intent(MediaStore.ActionImageCapture);

            App._file = new Java.IO.File(App._dir, String.Format("myPhoto_{0}.jpg", Guid.NewGuid()));

            intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(App._file));

            StartActivityForResult(intent, 0);
        }
Esempio n. 8
0
        internal static AndroidUri GetShareableFileUri(FileBase file)
        {
            Java.IO.File sharedFile;
            if (FileProvider.IsFileInPublicLocation(file.FullPath))
            {
                // we are sharing a file in a "shared/public" location
                sharedFile = new Java.IO.File(file.FullPath);
            }
            else
            {
                var rootDir = FileProvider.GetTemporaryDirectory();

                // create a unique directory just in case there are multiple file with the same name
                var tmpDir = new Java.IO.File(rootDir, Guid.NewGuid().ToString("N"));
                tmpDir.Mkdirs();
                tmpDir.DeleteOnExit();

                // create the new temprary file
                var tmpFile = new Java.IO.File(tmpDir, file.FileName);
                tmpFile.DeleteOnExit();

                var fileUri = AndroidUri.Parse(file.FullPath);
                if (fileUri.Scheme == "content")
                {
                    using var stream     = Application.Context.ContentResolver.OpenInputStream(fileUri);
                    using var destStream = System.IO.File.Create(tmpFile.CanonicalPath);
                    stream.CopyTo(destStream);
                }
                else
                {
                    System.IO.File.Copy(file.FullPath, tmpFile.CanonicalPath);
                }

                sharedFile = tmpFile;
            }

            // create the uri, if N use file provider
            if (HasApiLevelN)
            {
                var providerAuthority = AppContext.PackageName + ".fileProvider";
                return(FileProvider.GetUriForFile(
                           AppContext.ApplicationContext,
                           providerAuthority,
                           sharedFile));
            }

            // use the shared file path created
            return(AndroidUri.FromFile(sharedFile));
        }
        protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            //from gallery
            if (mIsFromGalleryPressed)
            {
                if (resultCode == Result.Ok)
                {
                    //Stream stream = ContentResolver.OpenInputStream(data.Data);  // data parameter from method
                    //Bitmap bitmap = BitmapFactory.DecodeStream(stream);
                    // pic = FindViewById<ImageView>(Resource.Id.imageView2);
                    //pic.SetImageBitmap(bitmap);

                    //  pic = FindViewById<ImageView>(Resource.Id.imageView2);
                    pic = FindViewById <ImageView>(Resource.Id.imageView1);
                    pic.SetImageURI(data.Data);

                    mSaveImageUri = data.Data;
                    //  pic.Visibility = ViewStates.Visible;
                    mIsFromGalleryPressed = false;
                }
            }
            //from camera
            else
            {
                Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
                Uri    contentUri      = Uri.FromFile(App._file);
                mediaScanIntent.SetData(contentUri);
                SendBroadcast(mediaScanIntent);

                // Display in ImageView. We will resize the bitmap to fit the display.
                // Loading the full sized image will consume to much memory
                // and cause the application to crash.

                int height = Resources.DisplayMetrics.HeightPixels;
                int width  = pic.Height;
                App.bitmap = App._file.Path.LoadAndResizeBitmap(width, height);
                if (App.bitmap != null)
                {
                    pic.SetImageBitmap(App.bitmap);
                    mSaveImageUri = Uri.FromFile(App._file);
                    //   pic.Visibility = ViewStates.Visible;
                    App.bitmap = null;
                }
                // Dispose of the Java side bitmap.
                GC.Collect();
            }
        }
Esempio n. 10
0
        protected virtual void ShowFileFromLocalPath(string path, bool delete = false)
        {
            Java.IO.File f = new Java.IO.File(path);

            Uri uri;

            if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
            {
                uri = Uri.Parse("content://" + path);
            }
            else
            {
                Java.IO.File file = new Java.IO.File(path);
                file.SetReadable(true);
                //Android.Net.Uri uri = Android.Net.Uri.Parse("file://" + filePath);
                uri = Uri.FromFile(file);
            }

            var uri1 = FileProvider.GetUriForFile(MainActivity.MainActivityInstance.ApplicationContext, MainActivity.MainActivityInstance.ApplicationContext.PackageName + ".provider", f);
            var t    = uri1.Authority;


            Intent intent = new Intent(Intent.ActionView);

            intent.SetDataAndType(uri1, GetMimeType(uri1, path));
            intent.AddFlags(ActivityFlags.GrantReadUriPermission);
            intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);

            try
            {
                Application.Context.StartActivity(intent);
            }
            catch (ActivityNotFoundException e)
            {
            }
            catch (System.Exception)
            {
                throw;
            }
            finally
            {
                if (delete)
                {
                    Task.Delay(2000);
                    File.Delete(path);
                }
            }
        }
Esempio n. 11
0
        public void CameraMedia(string CameraForm)
        {
            Intent intent = new Intent(MediaStore.ActionImageCapture);

            AppClass._file = new Java.IO.File(AppClass._dir, String.Format("myPhoto_{0}.jpg", Guid.NewGuid()));

            string fullfilename = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath
                                  + "/" + Android.OS.Environment.DirectoryDownloads;

            fullfilename += "/" + String.Format("myPhoto_{0}.jpg", Guid.NewGuid());

            AppClass._file = new Java.IO.File(fullfilename);

            intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(AppClass._file));
            MainActivity.CameraForm = CameraForm;

            m_Activity.StartActivityForResult(intent, 0);
        }
        public static Uri GetOutputMediaFile(Context context, string subdir, string name, bool isPhoto, bool saveToAlbum)
        {
            subdir = subdir ?? String.Empty;

            if (String.IsNullOrWhiteSpace(name))
            {
                string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
                if (isPhoto)
                {
                    name = "IMG_" + timestamp + ".jpg";
                }
                else
                {
                    name = "VID_" + timestamp + ".mp4";
                }
            }

            string mediaType = (isPhoto) ? Environment.DirectoryPictures : Environment.DirectoryMovies;
            var    directory = saveToAlbum ? Environment.GetExternalStoragePublicDirectory(mediaType) : context.GetExternalFilesDir(mediaType);

            using (Java.IO.File mediaStorageDir = new Java.IO.File(directory, subdir))
            {
                if (!mediaStorageDir.Exists())
                {
                    if (!mediaStorageDir.Mkdirs())
                    {
                        throw new IOException("Couldn't create directory, have you added the WRITE_EXTERNAL_STORAGE permission?");
                    }

                    if (!saveToAlbum)
                    {
                        // Ensure this media doesn't show up in gallery apps
                        using (Java.IO.File nomedia = new Java.IO.File(mediaStorageDir, ".nomedia"))
                            nomedia.CreateNewFile();
                    }
                }

                return(Uri.FromFile(new Java.IO.File(GetUniquePath(mediaStorageDir.Path, name, isPhoto))));
            }
        }
Esempio n. 13
0
        internal static AndroidUri GetShareableFileUri(string filename)
        {
            Java.IO.File sharedFile;
            if (FileProvider.IsFileInPublicLocation(filename))
            {
                // we are sharing a file in a "shared/public" location
                sharedFile = new Java.IO.File(filename);
            }
            else
            {
                var rootDir = FileProvider.GetTemporaryDirectory();

                // create a unique directory just in case there are multiple file with the same name
                var tmpDir = new Java.IO.File(rootDir, Guid.NewGuid().ToString("N"));
                tmpDir.Mkdirs();
                tmpDir.DeleteOnExit();

                // create the new temprary file
                var tmpFile = new Java.IO.File(tmpDir, System.IO.Path.GetFileName(filename));
                System.IO.File.Copy(filename, tmpFile.CanonicalPath);
                tmpFile.DeleteOnExit();

                sharedFile = tmpFile;
            }

            // create the uri, if N use file provider
            if (HasApiLevelN)
            {
                var providerAuthority = AppContext.PackageName + ".fileProvider";
                return(FileProvider.GetUriForFile(
                           AppContext.ApplicationContext,
                           providerAuthority,
                           sharedFile));
            }

            // use the shared file path created
            return(AndroidUri.FromFile(sharedFile));
        }
Esempio n. 14
0
        private void TakePhoto()
        {
            Intent TakePhotoIntent = new Intent(MediaStore.ActionImageCapture);

            if (TakePhotoIntent.ResolveActivity(PackageManager) != null)
            {
                File PhotoFile = null;
                try
                {
                    PhotoFile = CreateImageFile();
                    Toast.MakeText(this, PhotoFile.AbsolutePath, ToastLength.Long).Show();
                } catch (IOException ex)
                {
                    Toast.MakeText(this, Resource.String.file_error, ToastLength.Short).Show();
                    return;
                }
                if (PhotoFile != null)
                {
                    TakePhotoIntent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(PhotoFile));
                    StartActivityForResult(TakePhotoIntent, RequestImageCapture);
                }
            }
        }
        internal static Task <MediaPickedEventArgs> GetMediaFileAsync(Context context, int requestCode, string action, bool isPhoto, ref Uri path, Uri data, bool saveToAlbum)
        {
            Task <Tuple <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();
                    string currentPath = path.Path;
                    pathFuture = TryMoveFileAsync(context, data, path, isPhoto, saveToAlbum).ContinueWith(t =>
                                                                                                          new Tuple <string, bool>(t.Result ? currentPath : null, false));
                }
                else
                {
                    pathFuture = TaskFromResult(new Tuple <string, bool>(path.Path, false));
                }
            }
            else if (data != null)
            {
                originalPath = data.ToString();
                path         = data;
                pathFuture   = GetFileForUriAsync(context, path, isPhoto, saveToAlbum);
            }
            else
            {
                pathFuture = TaskFromResult <Tuple <string, bool> >(null);
            }

            return(pathFuture.ContinueWith(t =>
            {
                string resultPath = t.Result.Item1;
                if (resultPath != null && File.Exists(t.Result.Item1))
                {
                    string aPath = null;
                    if (saveToAlbum)
                    {
                        aPath = resultPath;
                        try
                        {
                            var f = new Java.IO.File(resultPath);


                            //MediaStore.Images.Media.InsertImage(context.ContentResolver,
                            //    f.AbsolutePath, f.Name, null);

                            try
                            {
                                Android.Media.MediaScannerConnection.ScanFile(context, new [] { f.AbsolutePath }, null, context as MediaPickerActivity);

                                ContentValues values = new ContentValues();
                                values.Put(MediaStore.Images.Media.InterfaceConsts.Title, Path.GetFileNameWithoutExtension(f.AbsolutePath));
                                values.Put(MediaStore.Images.Media.InterfaceConsts.Description, string.Empty);
                                values.Put(MediaStore.Images.Media.InterfaceConsts.DateTaken, Java.Lang.JavaSystem.CurrentTimeMillis());
                                values.Put(MediaStore.Images.ImageColumns.BucketId, f.ToString().ToLowerInvariant().GetHashCode());
                                values.Put(MediaStore.Images.ImageColumns.BucketDisplayName, f.Name.ToLowerInvariant());
                                values.Put("_data", f.AbsolutePath);

                                var cr = context.ContentResolver;
                                cr.Insert(MediaStore.Images.Media.ExternalContentUri, values);
                            }
                            catch (Exception ex1)
                            {
                                Console.WriteLine("Unable to save to scan file: " + ex1);
                            }

                            var contentUri = Uri.FromFile(f);
                            var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile, contentUri);
                            context.SendBroadcast(mediaScanIntent);
                        }
                        catch (Exception ex2)
                        {
                            Console.WriteLine("Unable to save to gallery: " + ex2);
                        }
                    }

                    var mf = new MediaFile(resultPath, () =>
                    {
                        return File.OpenRead(resultPath);
                    }, deletePathOnDispose: t.Result.Item2, dispose: (dis) =>
                    {
                        if (t.Result.Item2)
                        {
                            try
                            {
                                File.Delete(t.Result.Item1);
                                // We don't really care if this explodes for a normal IO reason.
                            }
                            catch (UnauthorizedAccessException)
                            {
                            }
                            catch (DirectoryNotFoundException)
                            {
                            }
                            catch (IOException)
                            {
                            }
                        }
                    }, albumPath: aPath);
                    return new MediaPickedEventArgs(requestCode, false, mf);
                }
                else
                {
                    return new MediaPickedEventArgs(requestCode, new MediaFileNotFoundException(originalPath));
                }
            }));
        }