Search code examples
c#asp.netxamarinxamarin.formsxamarin.android

Xamarin Forms move an apk file from a server to external storage


If you can assist, please, I'm trying to move an APK file from a server to external storage.

i Faced this issue : Android.OS.FileUriExposedException: 'file:///storage/emulated/0/Download/MyAppApks/add.txt exposed beyond app through Intent.getData()'

  var dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
                    var apkDirectory = new Java.IO.File(dir, "MyAppApks");
                    apkDirectory.Mkdirs();


                    var client = new HttpClient();
                    var apkUrl = "http://**.**.**.**:2030/com.companyname.app1.apk";
                    var response = await client.GetAsync(apkUrl);


                    var apkFile = new Java.IO.File(apkDirectory, "com.companyname.app1.apk");
                    using (var stream = new FileStream(apkFile.AbsolutePath, FileMode.Create, FileAccess.Write))
                    {
                        await response.Content.CopyToAsync(stream);
                    }


                    var intent = new Intent(Intent.ActionView);
                    intent.SetDataAndType(Android.Net.Uri.FromFile(apkFile), "application/vnd.android.package-archive");
                    intent.SetFlags(ActivityFlags.NewTask);
                    Android.App.Application.Context.StartActivity(intent);

Solution

  • try this:

        using (var client = new WebClient())
        {
    
    client.Headers.Add ("user-agent", "other");
            client.DownloadFile("http://**.**.**.**:2030/com.companyname.app1.apk", Android.OS.Environment.DirectoryDownloads + "/com.companyname.app1.apk");
        }
        
        string apkFile = Android.OS.Environment.DirectoryDownloads + "/com.companyname.app1.apk";
        
        var intent = new Intent(Intent.ActionView);
                            intent.SetDataAndType(Android.Net.Uri.FromFile(apkFile), "application/vnd.android.package-archive");
                            intent.SetFlags(ActivityFlags.NewTask);
                            Android.App.Application.Context.StartActivity(intent);