Xamarin.Forms save file (pdf) in local storage and open with the default viewer

后端 未结 1 724
情歌与酒
情歌与酒 2020-12-20 06:47

Edited to fine the question

In Android, I need to download a pdf file to \"Documents\" folder and open it with the default program. I downloaded the

1条回答
  •  没有蜡笔的小新
    2020-12-20 07:24

    I found a way to save and open the file:

        /// 
        /// Save data bytes on "My documents" folder and open
        /// 
        /// Filename, for example: "Test.pdf"
        /// Array of bytes to save
        /// True if success or false if error
        public bool SaveAndOpen(string fileName, byte[] data)
        {
            try
            {
                // Get my downloads path
                string filePath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
    
                // Combine with filename
                string fullName = Path.Combine(filePath, fileName);
    
                // If the file exist on device delete it
                if (File.Exists(fullName))
                {
                    // Note: In the second run of this method, the file exists
                    File.Delete(fullName);
                }
    
                // Write bytes on "My documents"
                File.WriteAllBytes(fullName, data);
    
                // Get the uri for the saved file
                Android.Net.Uri file = Android.Support.V4.Content.FileProvider.GetUriForFile(
                    this,
                    this.PackageName + ".fileprovider",
                    new Java.IO.File(fileName));
                Intent intent = new Intent(Intent.ActionView);
                intent.SetDataAndType(file, "application/pdf");
                intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask | ActivityFlags.GrantReadUriPermission | ActivityFlags.NewTask);
                this.ApplicationContext.StartActivity(intent);
    
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: " + ex.Message + ex.StackTrace);
                return false;
            }
        }
    

    It's needed to request the permissions at runtime. I used Plugin.Permisions available on Nuget:

        Plugin.Permissions.PermissionsImplementation.Current.RequestPermissionsAsync(
             new Plugin.Permissions.Abstractions.Permission[]
             {
                 Plugin.Permissions.Abstractions.Permission.Storage,
                 Plugin.Permissions.Abstractions.Permission.MediaLibrary
             });
    

    Also add a provider in the AndroidManifest.xml file:

    
        
            
        
    
    

    In the same AndroidManifest add permisions for:

    
    
    
    

    And add an external path in Resources/xml/file_paths.xml

    
    

    Don't know if I have not needed permissions, but with this way works.

    0 讨论(0)
提交回复
热议问题