コード例 #1
0
        /// <summary>
        /// 执行下载
        /// </summary>
        public async void StartDownloadHandler()
        {
            _progressBar.Progress = 0;
            Progress <DownloadBytesProgress> progressReporter = new Progress <DownloadBytesProgress>();

            progressReporter.ProgressChanged += (s, args) => _progressBar.Progress = (int)(100 * args.PercentComplete);

            string     tarPath         = Android.OS.Environment.ExternalStorageDirectory + "/JYandroidpda.apk";
            Task <int> downloadTask    = DownloadHelper.CreateDownloadTask(tarPath, url_down, progressReporter);
            int        bytesDownloaded = await downloadTask;

            System.Diagnostics.Debug.WriteLine("Downloaded {0} bytes.", bytesDownloaded);
        }
コード例 #2
0
        async void StartDownloadHandler(object sender, EventArgs e)
        {
            ProgressBar.Progress = 0f;

            Progress <DownloadBytesProgress> progressReporter = new Progress <DownloadBytesProgress>();

            progressReporter.ProgressChanged += (s, args) => ProgressBar.Progress = args.PercentComplete;

            Task <int> downloadTask    = DownloadHelper.CreateDownloadTask(DownloadHelper.ImageToDownload, progressReporter);
            int        bytesDownloaded = await downloadTask;

            Debug.WriteLine("Downloaded {0} bytes.", bytesDownloaded);
        }
コード例 #3
0
        private async Task Download(RssEnCaso download, bool isManual)
        {
            var    uri            = new Uri(download.AudioBoomUrl);
            string filename       = System.IO.Path.GetFileName(uri.LocalPath);
            int    notificationId = new Random().Next();


            ISharedPreferences prefs       = PreferenceManager.GetDefaultSharedPreferences(this);
            ISaveAndLoadFiles  saveAndLoad = new SaveAndLoadFiles_Android();
            Bitmap             bm          = null;

            NotificationManager notificationManager = (NotificationManager)this.ApplicationContext.GetSystemService(Context.NotificationService);

            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                NotificationChannel mChannel = new NotificationChannel(channel_id, channel_name, NotificationImportance.Default)
                {
                    Description = channel_description,
                    LightColor  = Color.Red
                };
                mChannel.EnableLights(true);
                mChannel.SetShowBadge(true);
                notificationManager.CreateNotificationChannel(mChannel);
            }

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this.ApplicationContext, channel_id)
                                                 .SetAutoCancel(true)             // Dismiss from the notif. area when clicked
                                                 .SetContentTitle(download.Title) // Set its title
                                                 .SetSmallIcon(Resource.Mipmap.ic_launcher)
                                                 .SetProgress(100, 0, false)
                                                 .SetOnlyAlertOnce(true)
                                                 .SetContentText(this.ApplicationContext.GetString(Resource.String.download_service_downloading));

            if (bm != null)
            {
                builder.SetLargeIcon(bm);
            }

            if (isManual)
            {
                notificationManager.Notify(notificationId, builder.Build());
            }
            else
            {
                StartForeground(id, builder.Build());
            }

            int ant = 1;
            Progress <DownloadBytesProgress> progressReporter = new Progress <DownloadBytesProgress>();

            progressReporter.ProgressChanged += (s, args) =>
            {
                int perc = (int)(100 * args.PercentComplete);
                if (perc > ant)
                {
                    ant += 1;
                    builder.SetProgress(100, (int)(100 * args.PercentComplete), false);
                    if (isManual)
                    {
                        notificationManager.Notify(notificationId, builder.Build());
                    }
                    else
                    {
                        StartForeground(id, builder.Build());
                    }
                }
            };

            try
            {
                if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.M)
                {
                    Permission permissionCheck = this.ApplicationContext.CheckSelfPermission(Manifest.Permission.WriteExternalStorage);
                    if (permissionCheck != Permission.Granted)
                    {
                        throw new UnauthorizedAccessException();
                    }
                }
                Task <byte[]> downloadTask    = DownloadHelper.CreateDownloadTask(download.AudioBoomUrl, progressReporter);
                byte[]        bytesDownloaded = null;
                //try
                //{
                bytesDownloaded = await downloadTask;
                //}
                //catch (Exception ex1)
                //{
                //    if (ex1.Message.Contains("(404) Not Found"))
                //    {
                //        downloadTask = DownloadHelper.CreateDownloadTask(download.AudioBoomUrl, progressReporter);
                //        bytesDownloaded = await downloadTask;
                //    }
                //}

                ISaveAndLoadFiles saveFile = new SaveAndLoadFiles_Android();
                var path = saveFile.SaveByteAsync(filename, bytesDownloaded);

                MediaScannerConnection
                .ScanFile(this.ApplicationContext,
                          new string[] { path },
                          new string[] { "audio/*" }, null);

                var enCasoFile = LocalDatabase <EnCasoFile> .GetEnCasoFileDb().GetFirstUsingString("SavedFile", path);

                if (enCasoFile != null)
                {
                    LocalDatabase <EnCasoFile> .GetEnCasoFileDb().Delete(enCasoFile);
                }
                LocalDatabase <EnCasoFile> .GetEnCasoFileDb().Save(
                    new EnCasoFile()
                {
                    Title            = download.Title,
                    Description      = download.Description,
                    PubDate          = download.PubDate,
                    ImageUrl         = download.ImageUrl,
                    SavedFile        = path,
                    DownloadDateTime = DateTime.Now
                }
                    );

                Intent openIntent = new Intent(this.ApplicationContext, typeof(MainActivity));
                openIntent.PutExtra(General.ALARM_NOTIFICATION_EXTRA, (int)DownloadReturns.OpenFile);
                openIntent.PutExtra(General.ALARM_NOTIFICATION_FILE, path);
                openIntent.PutExtra(General.ALARM_NOTIFICATION_TITLE, download.Title);
                openIntent.PutExtra(General.ALARM_NOTIFICATION_IMAGE, download.ImageUrl);
                PendingIntent pIntent = PendingIntent.GetActivity(this.ApplicationContext, 0, openIntent, PendingIntentFlags.UpdateCurrent);

                builder
                .SetProgress(0, 0, false)
                .SetContentText(download.Description)
                .SetContentIntent(pIntent);

                notificationManager.Notify(notificationId, builder.Build());
            }
            catch (UnauthorizedAccessException)
            {
                builder
                .SetProgress(0, 0, false)
                .SetContentText(Resources.GetString(Resource.String.download_service_unauthorized_file_exception));
                notificationManager.Notify(notificationId, builder.Build());
            }
            catch (IOException)
            {
                builder
                .SetProgress(0, 0, false)
                .SetContentText(Resources.GetString(Resource.String.download_service_io_file_exception));
                notificationManager.Notify(notificationId, builder.Build());
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("full"))
                {
                    builder
                    .SetProgress(0, 0, false)
                    .SetContentText(Resources.GetString(Resource.String.download_service_disk_full));
                }
                else
                {
                    builder
                    .SetProgress(0, 0, false)
                    .SetContentText(Resources.GetString(Resource.String.download_service_lost_internet_connection));
                }
                if (isManual)
                {
                    notificationManager.Notify(notificationId, builder.Build());
                }
                else
                {
                    StartForeground(id, builder.Build());
                }
            }
        }