public async Task UpdateRss(bool forceUpdate, CancellationToken ct) { try { if (ct.IsCancellationRequested) { ct.ThrowIfCancellationRequested(); } DateTime dateTime = DateTime.ParseExact( prefs.GetString(General.MANUAL_LAST_SEARCH, "1984-10-12 14:00:00"), "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture); if (int.Parse(dateTime.Date.ToString("yyyyMMdd")) < int.Parse(DateTime.Now.ToString("yyyyMMdd")) || forceUpdate) { rssEnCaso = LocalDatabase <RssEnCaso> .GetRssEnCasoDb().GetAll(); RssEnCaso[] rssEnCasoI = await RssEnCaso.GetRssEnCasoAsync(false, ct); ISharedPreferencesEditor editor = prefs.Edit(); editor.PutString(General.MANUAL_LAST_SEARCH, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); editor.Apply(); RssEnCaso[] insertRecords = rssEnCasoI.Except(rssEnCaso, new RssEnCaso()).ToArray(); foreach (RssEnCaso ins in insertRecords) { if (ct.IsCancellationRequested) { ct.ThrowIfCancellationRequested(); } LocalDatabase <RssEnCaso> .GetRssEnCasoDb().Save(ins); } RssEnCaso[] deleteRecords = rssEnCaso.Except(rssEnCasoI, new RssEnCaso()).ToArray(); foreach (RssEnCaso del in deleteRecords) { if (ct.IsCancellationRequested) { ct.ThrowIfCancellationRequested(); } LocalDatabase <RssEnCaso> .GetRssEnCasoDb().Delete(del); } manualRecyclerAdapter.UpdateData(rssEnCasoI); } } catch (WebException we) { Analytics.TrackEvent(we.Message); throw we; } catch (Exception ex) { Analytics.TrackEvent(ex.Message); throw ex; } }
public static DownloadReturns ExecuteDownload(Context context, RssEnCaso rssEnCaso, bool onlyWiFi, bool isManual) { if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.M) { Permission permissionCheck = context.CheckSelfPermission(Manifest.Permission.WriteExternalStorage); if (permissionCheck != Permission.Granted) { return(DownloadReturns.NoWritePermission); } } NetworkDetection networkDetection = NetworkDetection.DetectNetwork(context); if (!networkDetection.IsOnline) { return(DownloadReturns.NoInternetConection); } if (onlyWiFi && !networkDetection.IsWifi) { return(DownloadReturns.NoWiFiFound); } Intent downloadIntent = new Intent(context, typeof(DownloadService)); // Flag to start service if (isManual) { downloadIntent.SetAction(General.DOWNLOAD_START_SERVICE); } else { downloadIntent.SetAction(General.DOWNLOAD_START_AUTO); } // Passing values to intent downloadIntent.PutExtra("file", rssEnCaso.Url); downloadIntent.PutExtra("audioboomurl", rssEnCaso.AudioBoomUrl); downloadIntent.PutExtra("title", rssEnCaso.Title); downloadIntent.PutExtra("description", rssEnCaso.Description); downloadIntent.PutExtra("imageurl", rssEnCaso.ImageUrl); downloadIntent.PutExtra("pubdate", rssEnCaso.PubDate.ToString()); // Starting service context.StartService(downloadIntent); return(DownloadReturns.ServiceStarted); }
//[return: GeneratedEnum] public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId) { string extraDate = intent.GetStringExtra("pubdate"); DateTime.TryParse(extraDate, out DateTime pubDate); var rssEnCaso = new RssEnCaso() { Url = intent.GetStringExtra("file"), Title = intent.GetStringExtra("title"), Description = intent.GetStringExtra("description"), ImageUrl = intent.GetStringExtra("imageurl"), AudioBoomUrl = intent.GetStringExtra("audioboomurl"), PubDate = pubDate // downloadDateTime = DateTime.Now }; if (intent.Action.Equals(General.DOWNLOAD_START_AUTO)) { downloadList.Enqueue(rssEnCaso); if (!isRunning) { RegisterForegroundService(); isRunning = true; DownloadList(false); } } else if (intent.Action.Equals(General.DOWNLOAD_START_SERVICE)) { downloadList.Enqueue(rssEnCaso); PendingDownloads(); if (!isRunning) { RegisterForegroundService(); isRunning = true; DownloadList(true); } } else if (intent.Action.Equals(General.DOWNLOAD_STOP_SERVICE)) { StopMe(); } return(StartCommandResult.Sticky); }
private async void DialogPositiveButtonClick(object sender, DialogClickEventArgs dialogClickEventArgs) { ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this); bool isWiFi = prefs.GetBoolean(General.ALARM_ONLY_WIFI, true); try { CancellationTokenSource token = new CancellationTokenSource(); RssEnCaso[] rssEnCasos = await RssEnCaso.GetRssEnCasoAsync(true, token.Token); if (rssEnCasos.Length > 0) { DownloadReturns downloadReturns = General.ExecuteDownload(this, rssEnCasos[0], isWiFi, true); string notificationMessage = ""; switch (downloadReturns) { case DownloadReturns.NoInternetConection: notificationMessage = this.GetString(Resource.String.download_error_no_internet_conection); break; case DownloadReturns.NoWiFiFound: notificationMessage = this.GetString(Resource.String.download_error_no_wifi_found); break; case DownloadReturns.NoWritePermission: notificationMessage = this.GetString(Resource.String.download_error_no_write_permission); break; } if (!string.IsNullOrEmpty(notificationMessage)) { Toast.MakeText(this, notificationMessage, ToastLength.Long).Show(); } } } catch (WebException we) { Analytics.TrackEvent(we.Message); } }
public async override void OnReceive(Context context, Intent intent) { General.ProgramNextAlarm(context); ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(context); bool isWiFi = prefs.GetBoolean(General.ALARM_ONLY_WIFI, true); RssEnCaso rssEnCaso = null; try { CancellationTokenSource cts = new CancellationTokenSource(); RssEnCaso[] rssEnCasos = await RssEnCaso.GetRssEnCasoAsync(true, cts.Token); rssEnCaso = rssEnCasos[0]; } catch (WebException we) { Intent callIntent = new Intent(context, typeof(MainActivity)); callIntent.PutExtra(General.ALARM_NOTIFICATION_EXTRA, (int)DownloadReturns.NoInternetConection); PendingIntent pendingIntent = PendingIntent.GetActivity(context, 0, callIntent, PendingIntentFlags.UpdateCurrent); string notificationMessage = context.GetString(Resource.String.download_error_no_internet_conection); General.ShowNotification(context, notificationMessage, Resource.Drawable.main_nav_list, pendingIntent); Analytics.TrackEvent(we.Message); } if (rssEnCaso != null) { DownloadReturns downloadReturns = General.ExecuteDownload(context, rssEnCaso, isWiFi, false); string notificationMessage = ""; Intent callIntent = new Intent(context, typeof(MainActivity)); switch (downloadReturns) { case DownloadReturns.NoInternetConection: callIntent.PutExtra(General.ALARM_NOTIFICATION_EXTRA, (int)DownloadReturns.NoInternetConection); notificationMessage = context.GetString(Resource.String.download_error_no_internet_conection); break; case DownloadReturns.NoWiFiFound: callIntent.PutExtra(General.ALARM_NOTIFICATION_EXTRA, (int)DownloadReturns.NoWiFiFound); notificationMessage = context.GetString(Resource.String.download_error_no_wifi_found); break; case DownloadReturns.NoWritePermission: callIntent.PutExtra(General.ALARM_NOTIFICATION_EXTRA, (int)DownloadReturns.NoWritePermission); notificationMessage = context.GetString(Resource.String.download_error_no_write_permission); break; case DownloadReturns.ServiceStarted: callIntent = null; break; } if (callIntent != null) { PendingIntent pendingIntent = PendingIntent.GetActivity(context, 0, callIntent, PendingIntentFlags.UpdateCurrent); General.ShowNotification(context, notificationMessage, Resource.Drawable.main_nav_list, pendingIntent); } } //var jobScheduler = (JobScheduler)context.GetSystemService(Context.JobSchedulerService); //var javaClass = Java.Lang.Class.FromType(typeof(DownloadJobService)); //var componentName = new ComponentName(context, javaClass); //var jobInfo = new JobInfo // .Builder(1, componentName) // .SetMinimumLatency(1000) // .SetOverrideDeadline(2000) // .SetRequiredNetworkType(NetworkType.Any) // .SetRequiresDeviceIdle(false) // .SetRequiresCharging(false) // .Build(); //var scheduleResult = jobScheduler.Schedule(jobInfo); //if (JobScheduler.ResultSuccess == scheduleResult) //{ //} //else //{ //} }
public override bool OnStartJob(JobParameters @params) { Task.Run(async() => { ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this.ApplicationContext); bool isWiFi = prefs.GetBoolean(General.ALARM_ONLY_WIFI, true); RssEnCaso rssEnCaso = null; try { CancellationTokenSource cts = new CancellationTokenSource(); RssEnCaso[] rssEnCasos = await RssEnCaso.GetRssEnCasoAsync(true, cts.Token); rssEnCaso = rssEnCasos[0]; } catch (WebException we) { Intent callIntent = new Intent(this.ApplicationContext, typeof(MainActivity)); callIntent.PutExtra(General.ALARM_NOTIFICATION_EXTRA, (int)DownloadReturns.NoInternetConection); PendingIntent pendingIntent = PendingIntent.GetActivity(this.ApplicationContext, 0, callIntent, PendingIntentFlags.UpdateCurrent); string notificationMessage = this.ApplicationContext.GetString(Resource.String.download_error_no_internet_conection); General.ShowNotification(this.ApplicationContext, notificationMessage, Resource.Drawable.main_nav_list, pendingIntent); Analytics.TrackEvent(we.Message); } if (rssEnCaso != null) { DownloadReturns downloadReturns = General.ExecuteDownload(this.ApplicationContext, rssEnCaso, isWiFi, false); string notificationMessage = ""; Intent callIntent = new Intent(this.ApplicationContext, typeof(MainActivity)); switch (downloadReturns) { case DownloadReturns.NoInternetConection: callIntent.PutExtra(General.ALARM_NOTIFICATION_EXTRA, (int)DownloadReturns.NoInternetConection); notificationMessage = this.ApplicationContext.GetString(Resource.String.download_error_no_internet_conection); break; case DownloadReturns.NoWiFiFound: callIntent.PutExtra(General.ALARM_NOTIFICATION_EXTRA, (int)DownloadReturns.NoWiFiFound); notificationMessage = this.ApplicationContext.GetString(Resource.String.download_error_no_wifi_found); break; case DownloadReturns.NoWritePermission: callIntent.PutExtra(General.ALARM_NOTIFICATION_EXTRA, (int)DownloadReturns.NoWritePermission); notificationMessage = this.ApplicationContext.GetString(Resource.String.download_error_no_write_permission); break; case DownloadReturns.ServiceStarted: callIntent = null; break; } if (callIntent != null) { PendingIntent pendingIntent = PendingIntent.GetActivity(this.ApplicationContext, 0, callIntent, PendingIntentFlags.UpdateCurrent); General.ShowNotification(this.ApplicationContext, notificationMessage, Resource.Drawable.main_nav_list, pendingIntent); } } // Have to tell the JobScheduler the work is done. JobFinished(@params, false); }); return(true); }
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()); } } }