BackgroundTaskDeferral _deferral; // Note: defined at class scope so we can mark it complete inside the OnCancel() callback if we choose to support cancellation public async void Run(IBackgroundTaskInstance taskInstance) { _deferral = taskInstance.GetDeferral(); // // TODO: Insert code to start one or more asynchronous methods using the // await keyword, for example: // // await ExampleMethodAsync(); // //获取第一条博客 List <News> news = await NewsService.GetHotNewsDataArticlesAsync(1); var lastNews = news.LastOrDefault(); bool needPostNotifition = NeedPostNotifition(lastNews); if (needPostNotifition) //推送过,且未包含感兴趣的新闻,则通知 { //更新磁铁 string url = (await NewsService.GetNewsBodyAsync(lastNews.Id)).ImageUrl; //可能有多个图片用;分割,且以//开头,去掉// //images2015.cnblogs.com/news/66372/201701/66372-20170105220153644-24320897.jpg; if (!url.IsNullOrEmpty()) { url = "http://" + url.Split(';')[0].TrimStart('/'); } //string locaFileName = await ImageStorageHelper.GetLocalImageName(url); //if (locaFileName.IsNullOrEmpty()) //{ // //不存在缓存时才通知 // url = await Core.HttpHelper.DownloadImage(url); //} string command = new QueryString() { { "action", "HotNews" }, { "queryString", JsonSerializeHelper.Serialize(lastNews) } }.ToString(); ToastNotificationHelper.PushToastNotification(command, lastNews.Id, lastNews.Title, lastNews.Summary, lastNews.TopicIcon, url); //加入最后推送缓存 RoamingSetting.Current.SetSetting("LastNotifitionNewsId", lastNews.Id); } // _deferral.Complete(); }
private void OnResuming(object sender, object e) { var currentFrame = Window.Current.Content as Frame; var database = DatabaseService.Instance; try { database.ReOpen(); #if DEBUG ToastNotificationHelper.ShowGenericToast(database.Name, "Database reopened (changes were saved)"); #endif } catch (Exception) { currentFrame?.Navigate(typeof(MainPage10)); #if DEBUG ToastNotificationHelper.ShowGenericToast("App resumed", "Nothing to do, no previous database opened"); #endif } }
private async Task MarkEpWatched(string episodeId) { try { BangumiApi.Init( Constants.ClientId, Constants.ClientSecret, Constants.RedirectUrl, ApplicationData.Current.LocalFolder.Path, ApplicationData.Current.LocalCacheFolder.Path, EncryptionHelper.EncryptionAsync, EncryptionHelper.DecryptionAsync); await BangumiApi.BgmApi.UpdateProgress(episodeId, Api.Models.EpStatusType.watched); } catch (Exception e) { ToastNotificationHelper.Toast("操作失败", e.Message, "重试", _queryString); } }
/// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private async void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); var database = DatabaseService.Instance; try { if (SettingsService.Instance.GetSetting("SaveSuspend", true)) { database.Save(); } database.Close(false); } catch (Exception exception) { ToastNotificationHelper.ShowErrorToast(exception); } await SuspensionManager.SaveAsync(); deferral.Complete(); }
/// <summary> /// The Run method is the entry point of a background task. /// </summary> public async void Run(IBackgroundTaskInstance taskInstance) { Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting..."); // Query BackgroundWorkCost // Guidance: If BackgroundWorkCost is high, then perform only the minimum amount // of work in the background task and return immediately. var cost = BackgroundWorkCost.CurrentBackgroundWorkCost; // Associate a cancellation handler with the background task. taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled); // Get the deferral object from the task instance, and take a reference to the taskInstance; _deferral = taskInstance.GetDeferral(); _taskInstance = taskInstance; try { BangumiApi.Init( Constants.ClientId, Constants.ClientSecret, Constants.RedirectUrl, ApplicationData.Current.LocalFolder.Path, ApplicationData.Current.LocalCacheFolder.Path, EncryptionHelper.EncryptionAsync, EncryptionHelper.DecryptionAsync); await BangumiApi.BgmOAuth.CheckToken(); if (SettingHelper.EnableBangumiAirToast) { // 初始化 BangumiData 对象 BangumiData.Init(Path.Combine(ApplicationData.Current.LocalFolder.Path, "bangumi-data"), SettingHelper.UseBiliApp); if (!BangumiApi.BgmCache.IsUpdatedToday) { // 加载缓存,后面获取新数据后比较需要使用 var cachedWatchings = BangumiApi.BgmCache.Watching(); // 加载新的收视进度 var newWatching = await BangumiApi.BgmApi.Watching(); var subjectTasks = new List <Task <SubjectLarge> >(); var progressTasks = new List <Task <Progress> >(); // 新的收视进度与缓存的不同或未缓存的条目 var watchingsNotCached = BangumiApi.BgmCache.IsUpdatedToday ? newWatching.Where(it => cachedWatchings.All(it2 => !it2.EqualsExT(it))).ToList() : newWatching; using (var semaphore = new SemaphoreSlim(10)) { foreach (var item in watchingsNotCached) { await semaphore.WaitAsync(); subjectTasks.Add(BangumiApi.BgmApi.SubjectEp(item.SubjectId.ToString()) .ContinueWith(t => { semaphore.Release(); return(t.Result); })); await semaphore.WaitAsync(); progressTasks.Add(BangumiApi.BgmApi.Progress(item.SubjectId.ToString()) .ContinueWith(t => { semaphore.Release(); return(t.Result); })); } await Task.WhenAll(subjectTasks); await Task.WhenAll(progressTasks); } BangumiApi.BgmCache.IsUpdatedToday = true; await BangumiApi.BgmCache.WriteToFile(); } ToastNotificationHelper.RemoveAllScheduledToasts(); foreach (var item in CachedWatchProgress()) { await item.ScheduleToast(); } } } catch (BgmUnauthorizedException e) { // 取消所有后台任务 foreach (var cur in BackgroundTaskRegistration.AllTasks) { cur.Value.Unregister(true); } ToastNotificationHelper.Toast("后台任务", "用户认证过期,后台任务已取消。"); Debug.WriteLine(e.StackTrace); } catch (Exception ex) { Debug.WriteLine(ex.StackTrace); } finally { _deferral.Complete(); } IEnumerable <WatchProgress> CachedWatchProgress() { foreach (var watching in BangumiApi.BgmCache.Watching()) { var subject = BangumiApi.BgmCache.Subject(watching.SubjectId.ToString()); var progress = BangumiApi.BgmCache.Progress(watching.SubjectId.ToString()); var item = WatchProgress.FromWatching(watching); item.ProcessEpisode(subject); item.ProcessProgress(progress); if (subject == null || progress == null) { // 标记以重新加载 watching.Subject.Eps = -1; } yield return(item); } } }
/// <summary> /// Handles background task cancellation. /// </summary> private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) { ToastNotificationHelper.Toast("任务被取消", reason.ToString(), "重试", _queryString, ToastActivationType.Background); Debug.WriteLine("Background " + sender.Task.Name + " Cancel Requested..."); }
private async void OnLaunchedOrActivated(IActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // 不要在窗口已包含内容时重复应用程序初始化, // 只需确保窗口处于活动状态 if (rootFrame == null) { // 创建要充当导航上下文的框架,并导航到第一页 rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: 从之前挂起的应用程序加载状态 } // 将框架放在当前窗口中 Window.Current.Content = rootFrame; } // 处理正常启动 if (e is LaunchActivatedEventArgs launchActivatedArgs && launchActivatedArgs.PrelaunchActivated == false) { if (rootFrame.Content == null) { // 当导航堆栈尚未还原时,导航到第一页, // 并通过将所需信息作为导航参数传入来配置 // 参数 rootFrame.Navigate(typeof(MainPage), launchActivatedArgs.Arguments); } } // Handle toast activation if (e is ToastNotificationActivatedEventArgs toastActivationArgs) { if (rootFrame.Content == null) { rootFrame.Navigate(typeof(MainPage)); } // 等待加载完成 while (true) { if (MainPage.RootPage.IsLoaded) { break; } await Task.Delay(500); } // Parse the query string (using QueryString.NET) QueryString args = QueryString.Parse(toastActivationArgs.Argument); if (args.Contains("action")) { string id = string.Empty; // See what action is being requested switch (args["action"]) { // Open the subject case "viewSubject": id = args["subjectId"]; MainPage.RootPage.ResetFrameBackStack(); MainPage.RootPage.NavigateToPage(typeof(EpisodePage), args["subjectId"], null); break; case "gotoPlaySite": id = args["url"]; var sites = await BangumiData.GetAirSitesByBangumiIdAsync(id); await Launcher.LaunchUriAsync(new Uri(args["url"])); var episode = JsonConvert.DeserializeObject <EpisodeForSort>(args["episode"]); ToastNotificationHelper.Toast("看完了吗?", $"Ep.{episode.Sort} {Converters.StringOneOrTwo(episode.NameCn, episode.Name)}", "看完了!看完了!", "markEpWatched", "episodeId", episode.Id.ToString(), string.Empty, string.Empty, Microsoft.Toolkit.Uwp.Notifications.ToastActivationType.Background, true); break; } } } // 处理其它激活方式 // 确保当前窗口处于活动状态 Window.Current.Activate(); }