private void InstallVideo()
        {
            try
            {
                if (File.Exists(Path.Combine(storagePath, GetString(Resource.String.app_name), URLUtil.GuessFileName(videoPath, null, MimeTypeMap.GetFileExtensionFromUrl(videoPath)))))
                {
                    Toast.MakeText(this, GetString(Resource.String.video_already_downloaded), ToastLength.Short).Show();
                    return;
                }

                var request = new DownloadManager.Request(Uri.Parse(videoPath))
                              .SetTitle(statusTitle)
                              .SetDescription(GetString(Resource.String.load))
                              .SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted)
                              .SetDestinationInExternalPublicDir(Environment.DirectoryDownloads, Path.Combine(GetString(Resource.String.app_name), URLUtil.GuessFileName(videoPath, null, MimeTypeMap.GetFileExtensionFromUrl(videoPath))));

                ((DownloadManager)GetSystemService(DownloadService)).Enqueue(request);

                Toast.MakeText(this, GetString(Resource.String.video_downloaded_successfully), ToastLength.Short).Show();
            }
            catch
            {
                Toast.MakeText(this, GetString(Resource.String.error), ToastLength.Short).Show();
            }
        }
Esempio n. 2
0
File: Update.cs Progetto: UMI64/PINS
        private bool DownLoad(string Url)
        {
            try
            {
                /*检查是否有访问存储权限*/
                if (requestAllPower() == false)
                {
                    return(false);
                }

                DownloadManager.Request request = new DownloadManager.Request(Android.Net.Uri.Parse(Url));
                request.SetAllowedNetworkTypes(Android.App.DownloadNetwork.Wifi);//设定只有wifi环境下载
                request.SetTitle("我的下载");
                request.SetDescription("下载一个大文件");
                request.SetMimeType("application/vnd.android.package-archive");
                request.SetNotificationVisibility(Android.App.DownloadVisibility.Visible | Android.App.DownloadVisibility.VisibleNotifyCompleted);
                request.SetDestinationUri(Android.Net.Uri.FromFile(file));
                this.RunOnUiThread(() =>
                {
                    Toast.MakeText(this, "正在下载", ToastLength.Short).Show();
                });
                downloadId = downloadManager.Enqueue(request);
                return(true);
            }
            catch (Exception ex)
            {
                this.RunOnUiThread(() =>
                {
                    Toast.MakeText(this, ex.ToString(), ToastLength.Short).Show();
                });
                return(false);
            }
        }
        public void Download(string uri)
        {
            string filename = "";
            var    validate = uri;

            if (uri.Contains("idpdf"))
            {
                var name = uri.Replace("http://www.sadm.gob.mx/Solicitudes/solicitudcfdi?idpdf=", "");
                filename = name.Replace("/", "") + ".pdf";
            }
            else
            {
                var name = uri.Replace("http://www.sadm.gob.mx/Solicitudes/solicitudcfdi?idxml=", "");
                filename = name.Replace("/", "") + ".xml";
            }
            Android.Net.Uri contentUri = Android.Net.Uri.Parse(uri);

            DownloadManager.Request r = new DownloadManager.Request(contentUri);


            r.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads, filename);

            r.AllowScanningByMediaScanner();

            r.SetNotificationVisibility(Android.App.DownloadVisibility.VisibleNotifyCompleted);

            DownloadManager dm = (DownloadManager)Forms.Context.GetSystemService(Android.Content.Context.DownloadService);

            dm.Enqueue(r);
        }
Esempio n. 4
0
        /// <summary>
        /// Starts download of given URL
        /// </summary>
        /// <param name="url">URL of file to download</param>
        /// <param name="filename">filename of file to download</param>
        private void StartDownload(string url, string filename)
        {
            var uri     = global::Android.Net.Uri.Parse(url);
            var request = new DownloadManager.Request(uri);

            request.SetTitle(filename);
            request.SetDescription("Downloading file...");

            var cookie = CookieManager.Instance.GetCookie(url);

            request.AddRequestHeader("Cookie", cookie);

            if (global::Android.OS.Build.VERSION.SdkInt < global::Android.OS.BuildVersionCodes.Q)
            {
#pragma warning disable CS0618 // Type or member is obsolete
                request.AllowScanningByMediaScanner();
#pragma warning restore CS0618 // Type or member is obsolete
            }
            else
            {
                request.SetDestinationInExternalPublicDir(
                    global::Android.OS.Environment.DirectoryDownloads,
                    filename);
            }

            request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);

            var downloadManager = (DownloadManager)this.Context.GetSystemService(Context.DownloadService);
            downloadManager.Enqueue(request);

            Toast.MakeText(this.Context, "Image download started...", ToastLength.Short).Show();
        }
Esempio n. 5
0
        private void Webview_Download(object sender, DownloadEventArgs e)
        {
            try
            {
                var source = Android.Net.Uri.Parse(e.Url);

                var request = new DownloadManager.Request(source);

                request.AllowScanningByMediaScanner();

                request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);

                request.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads, source.LastPathSegment);

                var manager = (DownloadManager)this.GetSystemService(Context.DownloadService);

                manager.Enqueue(request);

                Toast.MakeText(this, "Downloading Indigent Reports", ToastLength.Short).Show();
            }

            catch (Exception ex)
            {
                Toast.MakeText(this, "Cannot Download the file", ToastLength.Short).Show();
                Console.WriteLine(ex.Message);
            };
        }
Esempio n. 6
0
        public void Download(IOListing io, Action <ResultState> complete)
        {
            this.AssurePath(io.FullPath);

            var dm = (DownloadManager)this.context.Activity.GetSystemService(Context.DownloadService);

            var uri = Android.Net.Uri.Parse(io.Url);

            var encodedUri = io.Url.Replace(uri.Path, Android.Net.Uri.Encode(uri.Path).Replace("%2F", "/"));

            var req = new DownloadManager.Request(Android.Net.Uri.Parse(encodedUri));

            var path = this.Map(io.FullPath);

            req.AllowScanningByMediaScanner();
            req.SetDestinationUri(Android.Net.Uri.FromFile(new File(path)));
            req.SetTitle(io.Name);

            var downlaodId = dm.Enqueue(req);

            Action <ResultState> action = state =>
            {
                complete.Invoke(state);
            };

            this.context.Activity.RegisterReceiver(
                new DownloadCompleteReceiver(action, downlaodId, this.userInteraction),
                new IntentFilter(DownloadManager.ActionDownloadComplete));
        }
        public SoundDownloadAsyncController(string url, string filename, long id, Context contextActivity)
        {
            try
            {
                ActivityContext = (HomeActivity)contextActivity;

                if (!Directory.Exists(FilePath))
                {
                    Directory.CreateDirectory(FilePath);
                }

                if (!filename.Contains(".mp3"))
                {
                    Filename = filename + ".mp3";
                }
                else
                {
                    Filename = filename;
                }

                SoundId         = id;
                DownloadManager = (DownloadManager)Application.Context.GetSystemService(Context.DownloadService);
                Request         = new DownloadManager.Request(Android.Net.Uri.Parse(url));
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
Esempio n. 8
0
        // static Java.Lang.Thread downloadThread;
        public static void DownloadFromLink(string url, string title, string toast = "", string ending = "", bool openFile = false, string descripts = "")
        {
            try {
                print("DOWNLOADING: " + url);

                DownloadManager.Request request = new DownloadManager.Request(Android.Net.Uri.Parse(url));
                request.SetTitle(title);
                request.SetDescription(descripts);
                string mainPath = Android.OS.Environment.DirectoryDownloads;
                string subPath  = title + ending;
                string fullPath = mainPath + "/" + subPath;

                print("PATH: " + fullPath);

                request.SetDestinationInExternalPublicDir(mainPath, subPath);
                request.SetVisibleInDownloadsUi(true);
                request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);

                DownloadManager manager;
                manager = (DownloadManager)MainActivity.activity.GetSystemService(Context.DownloadService);

                long downloadId = manager.Enqueue(request);

                // AUTO OPENS FILE WHEN DONE DOWNLOADING
                if (openFile || toast != "")
                {
                    Java.Lang.Thread downloadThread = new Java.Lang.Thread(() => {
                        try {
                            bool exists = false;
                            while (!exists)
                            {
                                try {
                                    string p = manager.GetUriForDownloadedFile(downloadId).Path;
                                    exists   = true;
                                }
                                catch (System.Exception) {
                                    Java.Lang.Thread.Sleep(100);
                                }
                            }
                            Java.Lang.Thread.Sleep(1000);
                            if (toast != "")
                            {
                                App.ShowToast(toast);
                            }
                            if (openFile)
                            {
                                print("OPEN FILE");
                                string truePath = (Android.OS.Environment.ExternalStorageDirectory + "/" + fullPath);
                                OpenFile(truePath);
                            }
                        }
                        catch { }
                    });
                    downloadThread.Start();
                }
            }
            catch (Exception _ex) {
                error(_ex);
            }
        }
        public VideoDownloadAsyncController(string url, string filename, Activity contextActivity, string fromActivity)
        {
            try
            {
                if (fromActivity == "Main")
                {
                    ActivityContext = TabbedMainActivity.GetInstance();
                }
                else if (fromActivity == "GlobalPlayer")
                {
                    ActivityContext = GlobalPlayerActivity.GetInstance();
                }
                else
                {
                    ActivityContext = contextActivity;
                }

                if (!Directory.Exists(FilePath))
                {
                    Directory.CreateDirectory(FilePath);
                }

                if (!filename.Contains(".mp4") || !filename.Contains(".Mp4") || !filename.Contains(".MP4"))
                {
                    Filename = filename + ".mp4";
                }

                Downloadmanager = (DownloadManager)ActivityContext.GetSystemService(Context.DownloadService);
                Request         = new DownloadManager.Request(Android.Net.Uri.Parse(url));
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
Esempio n. 10
0
 private long CreateSystemDownloadTask(string url, Java.IO.File saveFile, string Referer, string title = "")
 {
     try
     {
         DownloadManager         downloadManager = (DownloadManager)Forms.Context.GetSystemService(Context.DownloadService);
         DownloadManager.Request request         = new DownloadManager.Request(Android.Net.Uri.Parse(url));
         if (title.Length != 0)
         {
             request.SetTitle(title);
         }
         //从360云盘返回的地址不能加Referer下载
         if (!url.Contains("360.cn"))
         {
             request.AddRequestHeader("Referer", Referer);
         }
         request.AddRequestHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36");
         request.SetDestinationUri(Android.Net.Uri.FromFile(saveFile));
         request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
         long downloadId = downloadManager.Enqueue(request);
         return(downloadId);
     }
     catch (Exception ex)
     {
         return(0);
     }
 }
Esempio n. 11
0
        private void BtnDownload_Click(object sender, EventArgs e)
        {
            FileDelete();

            var manager = DownloadManager.FromContext(this);

            var url = new System.Uri(string.Format(@"{0}{1}", "http://172.34.34.144:8080/barcodescanner", string.Format("{0}{1}{2}", "/", Application.Context.PackageName, ".apk")));

            //var url = new System.Uri(string.Format(@"{0}{1}", "http://172.34.34.144:8080/barcodescanner", string.Format("{0}{1}", "/", "com.daesangit.barcodescanner.apk")));

            try
            {
                var request = new DownloadManager.Request(Android.Net.Uri.Parse(url.ToString()));
                request.SetMimeType("application/vnd.android.package-archive");
                request.SetTitle("App Download");
                request.SetDescription("File Downloading...");
                request.SetAllowedNetworkTypes(DownloadNetwork.Wifi | DownloadNetwork.Mobile);
                request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
                request.SetAllowedOverMetered(true);
                request.SetAllowedOverRoaming(true);

                request.SetDestinationUri(Android.Net.Uri.FromFile(new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath + string.Format("{0}{1}{2}", "/", Application.Context.PackageName, ".apk"))));

                System.Console.WriteLine(Android.OS.Environment.DirectoryDownloads);
                System.Console.WriteLine(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath);

                downloadId = manager.Enqueue(request);
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }
        }
Esempio n. 12
0
        public static long DownloadFile(string from, string to, DownloadManager dm)
        {
            //var uri = Android.Net.Uri.FromFile(new Java.IO.File(dir.AbsolutePath + to));
            var request = new DownloadManager.Request(Android.Net.Uri.Parse(from));

            request.SetDestinationInExternalPublicDir("Parlament/", to);
            return(dm.Enqueue(request));
        }
Esempio n. 13
0
 private long SetDownloadRequestToDownloadManager(Android.Net.Uri uri, DownloadManager manager)
 {
     DownloadManager.Request request = new DownloadManager.Request(Android.Net.Uri.Parse(Setting.apkPath));
     request.SetDescription("Plik instalacyjny CarRepairShopSupportSystem");
     request.SetTitle("CarRepairShopSupportSystem");
     request.SetDestinationUri(uri);
     return(manager.Enqueue(request));
 }
Esempio n. 14
0
        private long DownloadInvoice(Context context, Android.Net.Uri uri, string fileName)
        {
            DownloadManager downloadManager = DownloadManager.FromContext(context);
            var             request         = new DownloadManager.Request(uri);

            request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
            request.SetDestinationInExternalFilesDir(context, Android.OS.Environment.DirectoryDownloads, fileName + ".pdf");
            return(downloadManager.Enqueue(request));
        }
 public void OnDownloadStart(string url, string userAgent, string contentDisposition, string mimetype, long contentLength)
 {
     DownloadManager.Request request = new DownloadManager.Request(Android.Net.Uri.Parse(url));
     request.AllowScanningByMediaScanner();
     request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
     request.SetDestinationInExternalFilesDir(Forms.Context, Android.OS.Environment.DirectoryDownloads, "mydeddp.pdf");
     DownloadManager dm = (DownloadManager)Android.App.Application.Context.GetSystemService(Android.App.Application.DownloadService);
     dm.Enqueue(request);
 }
Esempio n. 16
0
        private void Download(Link l)
        {
            var source  = Android.Net.Uri.Parse(l.Url);
            var request = new DownloadManager.Request(source);

            request.AllowScanningByMediaScanner();
            request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
            request.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads, source.LastPathSegment);
            var manager = (DownloadManager)_Context.GetSystemService(Context.DownloadService);

            manager.Enqueue(request);
        }
        protected void Download(string title, string path, bool obsolete)
        {
            Console.WriteLine("Master Data Download URL: {0}", path);

            downloadManager = (DownloadManager)GetSystemService(DownloadService);
            CurrentRequest  = new DownloadManager.Request(Uri.Parse(path));
            CurrentRequest.SetTitle(title);
            CurrentRequest.SetDestinationInExternalFilesDir(this, "", CreateLocalFileName());
            downloadId = downloadManager.Enqueue(CurrentRequest);

            MonitorStatus();
        }
Esempio n. 18
0
        private void Download(string url, string dir)
        {
            var    downloadManager = (DownloadManager)context.GetSystemService(Context.DownloadService);
            string filename        = "pmi_download.pdf";

            context.RegisterReceiver(new Receiver(Path.Combine(dir, filename)), new IntentFilter(DownloadManager.ActionDownloadComplete));

            DownloadManager.Request request = new DownloadManager.Request(Android.Net.Uri.Parse(url));
            request.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads, filename);
            request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted); // to notify when download is complete

            downloadManager.Enqueue(request);
        }
        public bool DownloadFile(string uri)
        {
            var manager       = (DownloadManager)Android.App.Application.Context.GetSystemService(Context.DownloadService);
            var documents     = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            var directoryname = Path.Combine(documents, "Workshops");
            var path          = Path.Combine(directoryname, "file.mp4");
            var req           = new DownloadManager.Request(Android.Net.Uri.Parse(uri));

            req.SetDestinationInExternalFilesDir(Android.App.Application.Context, null, path);
            var ret = manager.Enqueue(req);

            return(true);
        }
Esempio n. 20
0
        public void descargar()
        {
            RunOnUiThread(() =>
            {
#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
                dialogoprogreso = new ProgressDialog(this);
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos
                dialogoprogreso.SetCanceledOnTouchOutside(false);
                dialogoprogreso.SetCancelable(false);
                dialogoprogreso.SetTitle("Obteniendo link de descarga del rom...");
                dialogoprogreso.SetMessage("Por favor espere");
                dialogoprogreso.Show();
            });


            var ruta = dicciopath[miselaneousmethods.consolelist[Intent.GetIntExtra("consoleindex", 0)]];
            if (!Directory.Exists(miselaneousmethods.cachepath))
            {
                Directory.CreateDirectory(miselaneousmethods.cachepath);
            }
            var link   = downloadlink;
            var manige = DownloadManager.FromContext(this);
            var requ   = new DownloadManager.Request(Android.Net.Uri.Parse(link.Replace(" ", "%20")));
            requ.SetDescription("Espere por favor");
            requ.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
            requ.SetTitle(nombre);
            Android.Net.Uri destino =
                Android.Net.Uri.FromFile(new Java.IO.File(ruta + "/" + Path.GetFileName(System.Net.WebUtility.UrlDecode(downloadlink).Replace(" ", ""))));
            requ.SetDestinationUri(destino);
            requ.SetVisibleInDownloadsUi(true);
            manige.Enqueue(requ);
            dialogoprogreso.Dismiss();
            RunOnUiThread(() => Toast.MakeText(this, "Descarga iniciada!!", ToastLength.Long).Show());
            miselaneousmethods.guardarenregistry(nombre, destino.Path, imagen, miselaneousmethods.consolelistformal[Intent.GetIntExtra("consoleindex", 0)], link.Replace(" ", "%20"));
            //  miselaneousmethods.guardarenregistrydescargas(nombre, destino.Path, imagen, consola.Text, link.Replace(" ", "%20"));
            new Thread(() =>
            {
                try
                {
                    using (WebClient cliente = new WebClient())
                    {
                        if (!Directory.Exists(miselaneousmethods.imgpath))
                        {
                            Directory.CreateDirectory(miselaneousmethods.imgpath);
                        }
                        cliente.DownloadFile(imagen, miselaneousmethods.imgpath + "/" + nombre + ".jpg");
                    }
                }
                catch (Exception) { }
            }).Start();
        }
        /// <summary>
        /// Download an apk from a given url and name it with the given version number
        /// </summary>
        /// <param name="urlOfTarget">The url of the apk</param>
        /// <param name="targetVersion">The version number to append</param>
        public void Download(string urlOfTarget, string targetVersion)
        {
            var uri          = Android.Net.Uri.Parse(urlOfTarget);
            var request      = new DownloadManager.Request(uri);
            var downloadName = this.PackageName + "." + targetVersion + ".apk";

            request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
            request.SetAllowedOverMetered(true);
            request.SetTitle(string.Format("App update, Version: {0}", targetVersion));
            request.SetDestinationInExternalFilesDir(this.context, Android.OS.Environment.DirectoryDownloads, downloadName);
            request.SetMimeType("application/vnd.android.package-archive");

            this.downloadReference = this.downloadManager.Enqueue(request);
        }
Esempio n. 22
0
        public void DownloadAndInstallApp(string downloadurl)
        {
            var savefilename = downloadurl.Substring(downloadurl.LastIndexOf("/", StringComparison.Ordinal) + 1);

            //  var path = Path.Combine(savedir, savefilename);


            DownloadManager.Request request =
                new DownloadManager.Request(Android.Net.Uri.Parse(downloadurl));
            request.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads, savefilename);
            // request.SetDestinationInExternalFilesDir(Application.Context, Android.OS.Environment.DirectoryDownloads, update. DownloadFileName);
            request.SetMimeType("application/vnd.android.package-archive");
            enqueeId = downloadManager.Enqueue(request);
        }
Esempio n. 23
0
        public async Task DownloadAndInstall(DownloadManager manager)
        {
            string url     = @"https://app.cforce.live/com.payforce.apk";
            var    source  = Android.Net.Uri.Parse(url);
            var    request = new DownloadManager.Request(source);

            request.AllowScanningByMediaScanner();
            request.SetAllowedOverRoaming(true);
            request.SetDescription("Downloading PayForce");
            request.SetAllowedOverMetered(true);
            request.SetVisibleInDownloadsUi(true);
            string filename = URLUtil.GuessFileName(url, null, MimeTypeMap.GetFileExtensionFromUrl(url));

            MainActivity.FileName = filename;
            request.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads, filename);
            request.SetNotificationVisibility(DownloadManager.Request.VisibilityVisibleNotifyCompleted);
            request.SetAllowedNetworkTypes(DownloadNetwork.Wifi | DownloadNetwork.Mobile);
            MainActivity.DownloadId = manager.Enqueue(request);
        }
Esempio n. 24
0
        private async Task <long?> EnqueueDownload(string url, string fileName)
        {
            if (!await new PermissionRequester().RequestStorageWrite())
            {
                return(null);
            }

            var source  = Android.Net.Uri.Parse(url);
            var request = new DownloadManager.Request(source);

            request.AllowScanningByMediaScanner();
            request.SetAllowedOverRoaming(false);
            request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
            request.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads, source.LastPathSegment);
            request.SetTitle(fileName);
            request.SetDescription(fileName);
            var manager = (DownloadManager)Application.Context.GetSystemService(Context.DownloadService);

            return(manager.Enqueue(request));
        }
Esempio n. 25
0
        // for now it only downloads ifunny
        public bool TryDownloadFile(string input, out Exception ex)
        {
            ex = null;
            try
            {
                var parser = ParserFinder.FindParser(this.ctx, input, out var url);

                if (parser == null)
                {
                    Toast.MakeText(ctx, "Incompatible site.", ToastLength.Short).Show();
                    return(false);
                }

                parser.TryFetchVideoUrl(url, out string[] urls);

                foreach (var _url in urls)
                {
                    var    uri           = Android.Net.Uri.Parse(_url);
                    var    request       = new DownloadManager.Request(uri);
                    string fileExtension = MimeTypeMap.GetFileExtensionFromUrl(_url);
                    string filename      = $"download.{fileExtension}";

                    request.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads,
                                                              $"DLBuddy/{parser.GetParserName()}/{filename}");

                    request.SetVisibleInDownloadsUi(true);
                    request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
                    request.SetTitle($"DLBuddy - {parser.GetParserName()}");
                    manager.Enqueue(request);
                }


                return(true);
            }
            catch (Exception e)
            {
                ex = e;
                return(false);
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Schedule the download of the big picture associated with the content. </summary>
        /// <param name="context"> any application context. </param>
        /// <param name="content"> content with big picture notification. </param>
        public static void downloadBigPicture(Context context, EngagementReachInteractiveContent content)
        {
            /* Set up download request */
            DownloadManager downloadManager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
            Uri             uri             = Uri.parse(content.NotificationBigPicture);

            DownloadManager.Request request = new DownloadManager.Request(uri);
            request.NotificationVisibility = DownloadManager.Request.VISIBILITY_HIDDEN;
            request.VisibleInDownloadsUi   = false;

            /* Create intermediate directories */
            File dir = context.getExternalFilesDir("engagement");

            dir = new File(dir, "big-picture");
            dir.mkdirs();

            /* Set destination */
            long contentId = content.LocalId;

            request.DestinationUri = Uri.fromFile(new File(dir, contentId.ToString()));

            /* Submit download */
            long id = downloadManager.enqueue(request);

            content.setDownloadId(context, id);

            /* Set up timeout on download */
            Intent intent = new Intent(EngagementReachAgent.INTENT_ACTION_DOWNLOAD_TIMEOUT);

            intent.putExtra(EngagementReachAgent.INTENT_EXTRA_CONTENT_ID, contentId);
            intent.Package = context.PackageName;
            PendingIntent operation       = PendingIntent.getBroadcast(context, (int)contentId, intent, 0);
            long          triggerAtMillis = SystemClock.elapsedRealtime() + DOWNLOAD_TIMEOUT;
            AlarmManager  alarmManager    = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

            alarmManager.set(ELAPSED_REALTIME_WAKEUP, triggerAtMillis, operation);
        }
        public VideoDownloadAsyncControler(string url, string filename, Context contextActivty)
        {
            try
            {
                if (!Directory.Exists(FilePath))
                {
                    Directory.CreateDirectory(FilePath);
                }

                if (!filename.Contains(".mp4") || !filename.Contains(".Mp4") || !filename.Contains(".MP4"))
                {
                    Filename = filename + ".mp4";
                }

                ContextActivty = contextActivty;

                Downloadmanager = (DownloadManager)Application.Context.GetSystemService(Context.DownloadService);
                Request         = new DownloadManager.Request(Android.Net.Uri.Parse(url));
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
Esempio n. 28
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.AutoUpdateLayout);

            progressBar = FindViewById <ProgressBar>(Resource.Id.progressBar1);
            textView1   = FindViewById <TextView>(Resource.Id.textView1);

            progressBar.Max = 100;
            textView1.Text  = "0 %";

            FileDelete();

            var manager = DownloadManager.FromContext(this);
            //var manager = (DownloadManager)GetSystemService(Context.DownloadService);

            var url = new System.Uri(string.Format(@"{0}{1}", GlobalSetting.Instance.MOBILEEndpoint.ToString(), string.Format("{0}{1}{2}", "/", Application.Context.PackageName, ".apk")));

            var request = new DownloadManager.Request(Android.Net.Uri.Parse(url.ToString()));

            request.SetMimeType("application/vnd.android.package-archive");
            request.SetTitle("App Download");
            request.SetDescription("File Downloading...");
            request.SetAllowedNetworkTypes(DownloadNetwork.Wifi | DownloadNetwork.Mobile);
            request.SetNotificationVisibility(DownloadVisibility.Visible);
            request.SetAllowedOverMetered(true); //모바일 네트쿼크
            request.SetAllowedOverRoaming(true); //로밍

            Java.IO.File path = this.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads);
            request.SetDestinationUri(Android.Net.Uri.FromFile(new Java.IO.File(path, string.Format("{0}{1}", Application.Context.PackageName, ".apk"))));

            downloadId = manager.Enqueue(request);

            Task.Run(() =>
            {
                for (; ;)
                {
                    var query = new DownloadManager.Query();
                    query.SetFilterById(downloadId);
                    ICursor cursor = manager.InvokeQuery(query);
                    if (cursor.MoveToFirst())
                    {
                        var soFar = cursor.GetDouble(cursor.GetColumnIndex(DownloadManager.ColumnBytesDownloadedSoFar));
                        var total = cursor.GetDouble(cursor.GetColumnIndex(DownloadManager.ColumnTotalSizeBytes));
                        RunOnUiThread(() =>
                        {
                            progressBar.SetProgress(System.Convert.ToInt32(soFar / total * 100), true);
                            textView1.Text = string.Format("{0} %", Convert.ToInt32(soFar / total * 100));
                        });
                        System.Console.WriteLine(soFar.ToString());

                        if (soFar.Equals(total))
                        {
                            break;
                        }
                    }
                    Thread.Sleep(500);
                }
            });
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.DownloadCollectionLayout);

            Button      goToPlayBtn = FindViewById <Button>(Resource.Id.goToPlayerBtn);
            ProgressBar progressBar = FindViewById <ProgressBar>(Resource.Id.progressBar1);
            TextView    textView    = FindViewById <TextView>(Resource.Id.textView1);
            TextView    dlLocation  = FindViewById <TextView>(Resource.Id.dlLocationTxt);

            //var downloadManager = CrossDownloadManager.Current;
            //var file = downloadManager.CreateDownloadFile("https://digitalb2017q3dev.blob.core.windows.net/prg-67/video/Black%20Label%20Ralph.mp4");
            //downloadManager.Start(file);

            //var documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            //var directoryname = Path.Combine(documents, "Videos");
            //var path = Path.Combine(directoryname, "video.mp4");

            //Better saving
            //string appDir = Android.App.Application.Context.GetExternalFilesDir(null).AbsolutePath;
            //var dlPath = Path.Combine(appDir, "Black-Label-Ralph.mp4");

            //string appDir = Application.Context.GetExternalFilesDir(Android.OS.Environment.DirectoryMovies).AbsolutePath;
            string appDir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryMovies).AbsolutePath;
            var    dlPath = Path.Combine(appDir, "Black-Label-Vid.mp4");

            DownloadManager downloadManager = (DownloadManager)Application.Context.GetSystemService(Context.DownloadService);

            DownloadManager.Request req = new DownloadManager.Request(
                Android.Net.Uri.Parse("https://digitalb2017q3dev.blob.core.windows.net/prg-67/video/Black%20Label%20Ralph.mp4")
                //Android.Net.Uri.Parse("http://ia800500.us.archive.org/33/items/Cartoontheater1930sAnd1950s1/PigsInAPolka1943.mp4")
                //Android.Net.Uri.Parse("android.resource://" + Application.PackageName + "/" + Resource.Raw.Lincoln)
                );

            //req.SetDestinationInExternalFilesDir(Application.Context, null, (string)Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryMovies) + "/Black-Label-Vid.mp4");
            req.SetDestinationUri(Android.Net.Uri.FromFile(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryMovies)));

            req.SetTitle("Black-Label-VIDEO");

            dlLocation.Text = "Downloading videos to: " + (string)Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryMovies);

            downloadManager.Enqueue(req);

            Task task = new Task(() =>
            {
                Thread.Sleep(30000);
                RunOnUiThread(() =>
                {
                    textView.Text          = "You are ready to watch! Let's begin...";
                    progressBar.Visibility = ViewStates.Invisible;
                    goToPlayBtn.Visibility = ViewStates.Visible;
                });
            });

            task.Start();

            goToPlayBtn.Click += delegate {
                StartActivity(typeof(VideoPlayerActivity));
            };
        }
	  /// <summary>
	  /// Schedule the download of the big picture associated with the content. </summary>
	  /// <param name="context"> any application context. </param>
	  /// <param name="content"> content with big picture notification. </param>
	  public static void downloadBigPicture(Context context, EngagementReachInteractiveContent content)
	  {
		/* Set up download request */
		DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
		Uri uri = Uri.parse(content.NotificationBigPicture);
		DownloadManager.Request request = new DownloadManager.Request(uri);
		request.NotificationVisibility = DownloadManager.Request.VISIBILITY_HIDDEN;
		request.VisibleInDownloadsUi = false;

		/* Create intermediate directories */
		File dir = context.getExternalFilesDir("engagement");
		dir = new File(dir, "big-picture");
		dir.mkdirs();

		/* Set destination */
		long contentId = content.LocalId;
		request.DestinationUri = Uri.fromFile(new File(dir, contentId.ToString()));

		/* Submit download */
		long id = downloadManager.enqueue(request);
		content.setDownloadId(context, id);

		/* Set up timeout on download */
		Intent intent = new Intent(EngagementReachAgent.INTENT_ACTION_DOWNLOAD_TIMEOUT);
		intent.putExtra(EngagementReachAgent.INTENT_EXTRA_CONTENT_ID, contentId);
		intent.Package = context.PackageName;
		PendingIntent operation = PendingIntent.getBroadcast(context, (int) contentId, intent, 0);
		long triggerAtMillis = SystemClock.elapsedRealtime() + DOWNLOAD_TIMEOUT;
		AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		alarmManager.set(ELAPSED_REALTIME_WAKEUP, triggerAtMillis, operation);
	  }
        public void descargar(string path, string archivo, string titulo, string link)
        {
            WebClient cliente2 = new WebClient();

            cliente2.DownloadFileAsync(new Uri("https://i.ytimg.com/vi/" + link.Split('=')[1] + "/mqdefault.jpg"), Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits/" + link.Split('=')[1]);
            //new
            if (titulo.Trim().Length > 45)
            {
                titulo = titulo.Remove(45);
            }
            tituloo = titulo;


            var manige = DownloadManager.FromContext(this);
            var requ   = new DownloadManager.Request(Android.Net.Uri.Parse(archivo));

            requ.SetDescription("Espere por favor");
            requ.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
            requ.SetTitle(tituloo);
            var destino = Android.Net.Uri.FromFile(new Java.IO.File(path));

            if (SettingsHelper.GetSetting("rutadescarga") == Android.OS.Environment.DirectoryDownloads)
            {
                requ.SetDestinationInExternalPublicDir(SettingsHelper.GetSetting("rutadescarga"), Path.GetFileName(path));
            }
            else
            {
                requ.SetDestinationUri(destino);
            }
            requ.AllowScanningByMediaScanner();

            requ.SetVisibleInDownloadsUi(true);



            manige.Enqueue(requ);

            if (Path.GetFileName(path).EndsWith(".mp3"))
            {
                ////////////////si es mp3
                string datosviejos = "";
                if (File.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d"))
                {
                    datosviejos = File.ReadAllText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d");
                }
                else
                {
                    var asss = File.Create(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d");
                    asss.Close();
                }
                if (!Directory.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits"))
                {
                    Directory.CreateDirectory(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits");
                }

                if (!datosviejos.Contains(link.Split('=')[1]))
                {
                    var aafff = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d");
                    aafff.Write(datosviejos + Path.GetFileNameWithoutExtension(path) + "²" + link + "²" + path + "¤");
                    aafff.Close();
                }
                else
                {
                    var datosparsed   = PlaylistsHelper.GetMedia(Constants.CachePath + "/downloaded.gr3d");
                    var videoid       = link.Split('=')[1];
                    int indexelemento = datosparsed.FindIndex(ax => ax.Link.Contains(videoid));
                    datosparsed[indexelemento].Path = path;
                    var aafff = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d");
                    aafff.Write(PlaylistsHelper.SerializeMedia(datosparsed));
                    aafff.Close();
                }
            }
            //////////////////////////////////////////////si es mp4
            else
            {
                string datosviejos = "";
                if (File.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2"))
                {
                    datosviejos = File.ReadAllText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2");
                }
                else
                {
                    var asss = File.Create(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2");
                    asss.Close();
                }
                if (!Directory.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits"))
                {
                    Directory.CreateDirectory(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits");
                }

                if (!datosviejos.Contains(link.Split('=')[1]))
                {
                    var aafff = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2");
                    aafff.Write(datosviejos + Path.GetFileNameWithoutExtension(path) + "²" + link + "²" + path + "¤");
                    aafff.Close();
                }
                else
                {
                    var datosparsed   = PlaylistsHelper.GetMedia(Constants.CachePath + "/downloaded.gr3d2");
                    var videoid       = link.Split('=')[1];
                    int indexelemento = datosparsed.FindIndex(ax => ax.Link.Contains(videoid));
                    datosparsed[indexelemento].Path = path;
                    var aafff = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2");
                    aafff.Write(PlaylistsHelper.SerializeMedia(datosparsed));
                    aafff.Close();
                }
                MultiHelper.ExecuteGarbageCollection();
            }



            /*
             * Random brandom = new Random();
             * WebClient cliente2= new WebClient();
             * cliente2.DownloadFileAsync(new Uri("https://i.ytimg.com/vi/" + link.Split('=')[1] + "/mqdefault.jpg"), Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits/" + link.Split('=')[1]);
             * int randum = brandom.Next(2000, 50000) + brandom.Next(2000, 50000);
             * random = randum;
             * try {
             *  NotificationManager notificationManager =
             *   GetSystemService(Context.NotificationService) as NotificationManager;
             *  if (titulo.Trim().Length > 30)
             *  {
             *      titulo = titulo.Remove(30);
             *  }
             *  tituloo = titulo;
             *  var builder = new Notification.Builder(ApplicationContext);
             *  builder.SetContentTitle("Descargando " + titulo + "...");
             *  builder.SetContentText("Espere por favor");
             *
             *  builder.SetSmallIcon(Resource.Drawable.downloadbutton);
             *
             *
             *
             *  WebClient cliente = new WebClient();
             *
             * byte[] losbits = null;
             *  cliente.DownloadProgressChanged += (aasd, asddd) =>
             *  {
             *
             *      builder.SetContentTitle("Descargando "+titulo+"...");
             *      builder.SetContentText("Espere por favor");
             *      builder.SetSmallIcon(Resource.Drawable.downloadbutton);
             *      builder.SetProgress(100, asddd.ProgressPercentage, false);
             *      notificationManager.Notify(randum, builder.Build());
             *
             *  };
             * cliente.DownloadDataCompleted += (aa, aaa) =>
             * {
             *
             *  //  Intent intentss = new Intent(this,typeof(actividadacciones));
             *  //  intentss.PutExtra("prro", path);
             *  try {
             *  var selectedUri = Android.Net.Uri.Parse( prefs.GetString("rutadescarga",null)+ "/");
             *
             *  Intent intentssdd = new Intent(this,typeof(actividadadinfooffline));
             *  intentssdd.PutExtra("nombre", Path.GetFileName(path));
             *  intentssdd.PutExtra("link", link);
             *  intentssdd.PutExtra("path", path);
             *
             *
             *
             *
             *
             *  PendingIntent intentosd = PendingIntent.GetActivity(this, brandom.Next(2000, 50000) + brandom.Next(2000, 50000), intentssdd, PendingIntentFlags.UpdateCurrent);
             *
             *
             *  builder.SetContentTitle("Descarga completada de: "+titulo);
             *  builder.SetContentText("Toque para abrir");
             *  builder.SetSmallIcon(Resource.Drawable.downloadbutton);
             *  builder.SetContentIntent(intentosd);
             *      builder.SetOngoing(false);
             *      notificationManager.Notify(randum, builder.Build());
             *
             *  losbits = aaa.Result;
             *  var a = File.Create(path);
             *  a.Write(losbits, 0, losbits.Length);
             *  a.Close();
             *  string datosviejos = "";
             *  link = link.Replace('²', ' ');
             *  link= link.Replace('¤', ' ');
             *  path =path.Replace('²', ' ');
             *  path=path.Replace('¤', ' ');
             *
             *
             *  if (Path.GetFileName(path).EndsWith(".mp3")) {
             *  ///////////////////////////si es mp3
             *
             *  if (File.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d"))
             *  {
             *     datosviejos = File.ReadAllText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d");
             *  }
             *  if (!Directory.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits"))
             *  {
             *      Directory.CreateDirectory(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits");
             *  }
             *
             *  if(!datosviejos.Contains(Path.GetFileNameWithoutExtension(path) + "²" + link + "²" + path + "¤"))
             *  {
             *      var aafff = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d");
             *      aafff.Write(datosviejos + Path.GetFileNameWithoutExtension(path) + "²" + link + "²" + path + "¤");
             *      aafff.Close();
             *
             *  }
             *
             *
             *  }
             *  //////////////////////////////////////////////si es mp4
             *  else
             *  {
             *      if (File.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2"))
             *      {
             *          datosviejos = File.ReadAllText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2");
             *      }
             *      if (!Directory.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits"))
             *      {
             *          Directory.CreateDirectory(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits");
             *      }
             *
             *      if (!datosviejos.Contains(Path.GetFileNameWithoutExtension(path) + "²" + link + "²" + path + "¤"))
             *      {
             *          var aafff = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2");
             *          aafff.Write(datosviejos + Path.GetFileNameWithoutExtension(path) + "²" + link + "²" + path + "¤");
             *          aafff.Close();
             *
             *      }
             *          clasesettings.recogerbasura();
             *  }
             *      completada = true;
             *  }
             *  catch (Exception)
             *  {
             *      clasesettings.recogerbasura();
             *      Toast.MakeText(this, "ha ocurrido un error al descargar intente de nuevo", ToastLength.Long).Show();
             *     // StopForeground(false);
             *  }
             *
             * };
             *
             *  cliente.DownloadData(new Uri(archivo));
             * }
             * catch (Exception)
             * {
             *  NotificationManager notificationManager =
             *  GetSystemService(Context.NotificationService) as NotificationManager;
             *  var builder = new Notification.Builder(ApplicationContext);
             *  builder.SetContentTitle("ERROR AL DESCARGAR: " + titulo);
             *  builder.SetContentText("Intente de nuevo");
             *  builder.SetSmallIcon(Resource.Drawable.downloadbutton);
             *  builder.SetOngoing(false);
             *  notificationManager.Notify(randum, builder.Build());
             *  clasesettings.recogerbasura();
             *
             * }
             */
        }