private static Task RequestExtendedExecutionAsync()
        {
            return(Task.Run(() =>
            {
                lock (sessionSyncRoot)
                {
                    if (extendedExeSession != null)
                    {
                        extendedExeSession.Dispose();
                        extendedExeSession = null;
                    }

                    var newSession = new ExtendedExecutionSession();
                    newSession.Reason = ExtendedExecutionReason.Unspecified;
                    newSession.Revoked += ExtendedExecutionRevoked;

                    var asyncTask = newSession.RequestExtensionAsync().AsTask();
                    asyncTask.Wait();
                    ExtendedExecutionResult result = asyncTask.Result;

                    switch (result)
                    {
                    case ExtendedExecutionResult.Allowed:
                        extendedExeSession = newSession;
                        break;

                    default:
                    case ExtendedExecutionResult.Denied:
                        newSession.Dispose();
                        break;
                    }
                }
            }));
        }
示例#2
0
        private async Task SaveData()
        {
            if (!UseCloudStorage)
            {
                SaveDataLocal();
            }
            else
            {
                ShowToast("Saving to cloud");

                if (ExtendedExecution)
                {
                    using (var session = new ExtendedExecutionSession())
                    {
                        session.Reason = ExtendedExecutionReason.SavingData;
                        session.Description = "uploading data";
                        session.Revoked += Session_Revoked; 
                        var res = await session.RequestExtensionAsync();
                        if (res == ExtendedExecutionResult.Allowed)
                            await SaveToCloud();
                    }
                }
                else
                    await SaveToCloud();
            }
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode == NavigationMode.New)
            {
                var extendedSession = new ExtendedExecutionSession();
                extendedSession.Reason = ExtendedExecutionReason.LocationTracking;
                extendedSession.Description = "Location tracking";
                extendedSession.Revoked += ExtendedSession_Revoked;

                ExtendedExecutionResult result = await extendedSession.RequestExtensionAsync();
                if (result == ExtendedExecutionResult.Allowed)
                {
                    Debug.WriteLine("Background execution approved");
                }
                else
                {
                    Debug.WriteLine("Background execution denied");
                }

                Geolocator locator = new Geolocator();
                locator.DesiredAccuracyInMeters = 0;
                locator.MovementThreshold = 500;
                locator.DesiredAccuracy = PositionAccuracy.High;
                locator.PositionChanged += Locator_PositionChanged;
            }
        }
示例#4
0
        private async void BeginExtendedExecution()
        {
            ClearExtendedExecution();

            var newSession = new ExtendedExecutionSession
            {
                Reason      = ExtendedExecutionReason.Unspecified,
                Description = "Keep Shokpod running in background"
            };

            newSession.Revoked += ExtendedExecutionSession_RevokedAsync;
            ExtendedExecutionResult result = await newSession.RequestExtensionAsync();

            switch (result)
            {
            case ExtendedExecutionResult.Allowed:
                MetroEventSource.ToastAsync("Request for background execution granted!");
                extendedExecutionSession = newSession;
                break;

            default:
            case ExtendedExecutionResult.Denied:
                MetroEventSource.ToastAsync("Request for background execution denied!");
                newSession.Dispose();
                break;
            }
        }
    private async void BeginExtendedExecution()
    {
        // The previous Extended Execution must be closed before a new one can be requested.
        // This code is redundant here because the sample doesn't allow a new extended
        // execution to begin until the previous one ends, but we leave it here for illustration.
        ClearExtendedExecution();

        var newSession = new ExtendedExecutionSession();

        newSession.Reason      = ExtendedExecutionReason.Unspecified;
        newSession.Description = "Raising periodic toasts";
        newSession.Revoked    += SessionRevoked;
        ExtendedExecutionResult result = await newSession.RequestExtensionAsync();

        switch (result)
        {
        case ExtendedExecutionResult.Allowed:
            session = newSession;
            Debug.Log("Extended Execution started succesfully");
            break;

        default:
        case ExtendedExecutionResult.Denied:
            newSession.Dispose();
            Debug.Log("Extended Execution denied!");
            break;
        }
    }
示例#6
0
        private async void BeginExtendedExecution()
        {
            // The previous Extended Execution must be closed before a new one can be requested.
            // This code is redundant here because the sample doesn't allow a new extended
            // execution to begin until the previous one ends, but we leave it here for illustration.
            ClearExtendedExecution();

            var newSession = new ExtendedExecutionSession();

            newSession.Reason      = ExtendedExecutionReason.Unspecified;
            newSession.Description = "Running time in the background";
            newSession.Revoked    += SessionRevoked;
            var result = await newSession.RequestExtensionAsync();

            switch (result)
            {
            case ExtendedExecutionResult.Allowed:
                session = newSession;
                break;

            default:
            case ExtendedExecutionResult.Denied:
                newSession.Dispose();
                break;
            }
        }
示例#7
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode == NavigationMode.New)
            {
                var extendedSession = new ExtendedExecutionSession();
                extendedSession.Reason      = ExtendedExecutionReason.LocationTracking;
                extendedSession.Description = "Location tracking";

                ExtendedExecutionResult result = await extendedSession.RequestExtensionAsync();

                if (result == ExtendedExecutionResult.Allowed)
                {
                    Debug.WriteLine("Background execution approved");
                }
                else
                {
                    Debug.WriteLine("Background execution denied");
                }

                Geolocator locator = new Geolocator();
                locator.DesiredAccuracyInMeters = 0;
                locator.MovementThreshold       = 500;
                locator.DesiredAccuracy         = PositionAccuracy.High;
                locator.PositionChanged        += Locator_PositionChanged;
            }
        }
        private async Task BeginExtendedExecution()
        {
            if (ViewModel == null)
            {
                return;
            }

            ClearExtendedExecution();

            var newSession = new ExtendedExecutionSession
            {
                Reason      = ExtendedExecutionReason.LocationTracking,
                Description = "Tracking your location"
            };

            newSession.Revoked += SessionRevoked;
            ExtendedExecutionResult result = await newSession.RequestExtensionAsync();

            switch (result)
            {
            case ExtendedExecutionResult.Allowed:
                session = newSession;
                ViewModel.Geolocator.AllowsBackgroundUpdates = true;
                ViewModel.StartTrackingTripCommand.Execute(null);

                break;

            default:
                Acr.UserDialogs.UserDialogs.Instance.Alert("Unable to execute app in the background.",
                                                           "Background execution denied.", "OK");

                newSession.Dispose();
                break;
            }
        }
示例#9
0
        private async void BeginExtendedExecution()
        {
            // The previous Extended Execution must be closed before a new one can be requested.
            ClearExtendedExecution();

            var newSession = new ExtendedExecutionSession();

            newSession.Reason      = ExtendedExecutionReason.Unspecified;
            newSession.Description = "Raising periodic toasts";
            newSession.Revoked    += SessionRevoked;
            ExtendedExecutionResult result = await newSession.RequestExtensionAsync();

            switch (result)
            {
            case ExtendedExecutionResult.Allowed:
                session = newSession;
                break;

            default:
            case ExtendedExecutionResult.Denied:
                newSession.Dispose();
                //建立Toast通知
                string          title   = "Pixiv Wallpaper for Windows 10活动被禁止";
                string          content = "由于系统限制,应用程序无法在后台继续活动。";
                ToastManagement tm      = new ToastManagement(title, content, ToastManagement.ErrorMessage);
                tm.ToastPush(120);
                break;
            }
        }
示例#10
0
        public MainPage()
        {
            this.InitializeComponent();
            mp             = this;
            c              = new Conf();
            img            = c.lastImg;
            session        = null;
            backgroundMode = c.backgroundMode;

            //后台模式选择
            if (backgroundMode.Equals("BackgroundTask"))
            {
                RegistTask(); //注册后台任务以及时间触发器
            }
            else
            {
                timer          = new DispatcherTimer();
                timer.Interval = TimeSpan.FromMinutes(c.time);
                timer.Tick    += Timer_Tick;
                timer.Start();
                BeginExtendedExecution(); //申请延迟挂起

                foreach (var i in BackgroundTaskRegistration.AllTasks.Values)
                {
                    if (i.Name.Equals("TimeBackgroundTrigger"))
                    {
                        i.Unregister(true);//将之前的时间触发器任务注销
                    }
                }
            }

            main.Navigate(typeof(ShowPage));
        }
示例#11
0
        public async void BeginExecutedExtension()
        {
            CancelExecutedExtension();

            newSession             = new ExtendedExecutionSession();
            newSession.Reason      = ExtendedExecutionReason.Unspecified;
            newSession.Description = "Timer Pomodoro Tomato";
            newSession.Revoked    += NewSession_Revoked;
            ExtendedExecutionResult result = await newSession.RequestExtensionAsync();

            switch (result)
            {
            case ExtendedExecutionResult.Allowed:
                tomato.Start();
                break;

            case ExtendedExecutionResult.Denied:
                Notifier.GetInstance(Dispatcher).ShowMessageNotification(NotificationType.Error, false);

                CancelExecutedExtension();

                tomato.Cancel();
                var loader = new Windows.ApplicationModel.Resources.ResourceLoader();

                ucStopNotice.ChangeMessage(loader.GetString("ToastInterrupt0/Text"));

                ShowStopNotice.Begin();


                break;
            }
        }
示例#12
0
        public async void ExtendExecution()
        {
            Debug.WriteLine("Attempting extension");
            try
            {
                if (session != null)
                {
                    session.Revoked -= Session_Revoked;
                    session.Dispose();
                    session = null;
                }

                session          = new ExtendedExecutionSession();
                session.Reason   = ExtendedExecutionReason.Unspecified;
                session.Revoked += Session_Revoked;
                ExtendedExecutionResult result = await session.RequestExtensionAsync();

                switch (result)
                {
                case ExtendedExecutionResult.Allowed:
                    break;

                default:
                case ExtendedExecutionResult.Denied:
                    SessionRevoked = true;
                    break;
                }
            }
            catch { }
        }
示例#13
0
        private async Task CheckExtendedExecution()
        {
            if (AskForExtendedExecutionOnNextSuspend)
            {
                AskForExtendedExecutionOnNextSuspend = false;
                using (var session = new ExtendedExecutionSession()
                {
                    Reason = ExtendedExecutionReason.SavingData
                })
                {
                    session.Revoked += (s, args) =>
                    {
                        AppLog.Write("extended execution revoked, reason: " + args.Reason);
                    };
                    session.Description = "toasting things up";

                    var extendedExecutionResult = await session.RequestExtensionAsync();

                    if (extendedExecutionResult == ExtendedExecutionResult.Allowed)
                    {
                        while (true)
                        {
                            await Task.Delay(TimeSpan.FromSeconds(10));

                            ShowStillAliveToast();
                        }
                    }
                }
            }
        }
        private async void BeginExtendedExecution()
        {
            // The previous Extended Execution must be closed before a new one can be requested.
            ClearExtendedExecution();

            var newSession = new ExtendedExecutionSession();

            newSession.Reason      = ExtendedExecutionReason.Unspecified;
            newSession.Description = "Raising periodic toasts";
            newSession.Revoked    += SessionRevoked;
            ExtendedExecutionResult result = await newSession.RequestExtensionAsync();

            switch (result)
            {
            case ExtendedExecutionResult.Allowed:
                session = newSession;
                break;

            default:
            case ExtendedExecutionResult.Denied:
                newSession.Dispose();
                //建立Toast通知
                string       title   = loader.GetString("ExtendedExecutionDenied");
                string       content = loader.GetString("ExtendedExcutionDeniedExplanation");
                ToastMessage tm      = new ToastMessage(title, content, ToastMessage.ToastMode.BatterySetting);
                tm.ToastPush(120);
                break;
            }
        }
示例#15
0
        private async void BeginExtendedExecution()
        {
            // https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/ExtendedExecution
            // The previous Extended Execution must be closed before a new one can be requested.
            // This code is redundant here because the sample doesn't allow a new extended
            // execution to begin until the previous one ends, but we leave it here for illustration.
            ClearExtendedExecution();

            var newSession = new ExtendedExecutionSession();

            newSession.Reason      = ExtendedExecutionReason.Unspecified;
            newSession.Description = "Raising periodic timer ticks";
            newSession.Revoked    += SessionRevoked;
            ExtendedExecutionResult result = await newSession.RequestExtensionAsync();

            switch (result)
            {
            case ExtendedExecutionResult.Allowed:
                _session       = newSession;
                _periodicTimer = new Timer(OnTimer, DateTime.Now, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
                break;

            default:
            case ExtendedExecutionResult.Denied:
                newSession.Dispose();
                break;
            }
        }
示例#16
0
        /// <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();

            try
            {
                // The synchronisation with the online storage needs possibly more time than
                // granted with e.SuspendingOperation.Deadline, so we request an extended session
                using (var extendedSession = new ExtendedExecutionSession())
                {
                    bool gotExtendedSession;
                    extendedSession.Reason      = ExtendedExecutionReason.SavingData;
                    extendedSession.Description = "Synchronization with the online storage.";
                    extendedSession.Revoked    += (object s, ExtendedExecutionRevokedEventArgs a) => gotExtendedSession = false;
                    gotExtendedSession          = await extendedSession.RequestExtensionAsync() == ExtendedExecutionResult.Allowed;

                    // Save application state and stop any background activity
                    INavigationService navigationService = Ioc.GetOrCreate <INavigationService>();
                    navigationService.CurrentController?.StoreUnsavedData();

                    if (gotExtendedSession)
                    {
                        IAutoSynchronizationService syncService = Ioc.GetOrCreate <IAutoSynchronizationService>();
                        await syncService.SynchronizeAtShutdown();
                    }
                }
            }
            catch
            {
            }
            deferral.Complete();
        }
示例#17
0
        private async void BeginExtendedExecution()
        {
            // The previous Extended Execution must be closed before a new one can be requested.
            // This code is redundant here because the sample doesn't allow a new extended
            // execution to begin until the previous one ends, but we leave it here for illustration.
            ClearExtendedExecution();

            var newSession = new ExtendedExecutionSession();

            newSession.Reason      = ExtendedExecutionReason.Unspecified;
            newSession.Description = "Raising periodic toasts";
            newSession.Revoked    += SessionRevoked;
            ExtendedExecutionResult result = await newSession.RequestExtensionAsync();

            switch (result)
            {
            case ExtendedExecutionResult.Allowed:
                rootPage.NotifyUser("Extended execution allowed.", NotifyType.StatusMessage);
                session       = newSession;
                periodicTimer = new Timer(OnTimer, DateTime.Now, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(10));
                break;

            default:
            case ExtendedExecutionResult.Denied:
                rootPage.NotifyUser("Extended execution denied.", NotifyType.ErrorMessage);
                newSession.Dispose();
                break;
            }
            UpdateUI();
        }
示例#18
0
        private async void BeginExtendedExecution(uint interval)
        {
            // The previous Extended Execution must be closed before a new one can be requested.
            // This code is redundant here because the sample doesn't allow a new extended
            // execution to begin until the previous one ends, but we leave it here for illustration.
            ClearExtendedExecution();

            var newSession = new ExtendedExecutionSession();

            newSession.Reason      = ExtendedExecutionReason.LocationTracking;
            newSession.Description = "Tracking your location";
            newSession.Revoked    += SessionRevoked;
            ExtendedExecutionResult result = await newSession.RequestExtensionAsync();

            switch (result)
            {
            case ExtendedExecutionResult.Allowed:
                this.NotifyUser("Extended execution allowed. Please navigate away from this app.", NotifyType.StatusMessage);
                session = newSession;
                Geolocator geolocator = await StartLocationTrackingAsync();

                periodicTimer = new Timer(OnTimer, geolocator, TimeSpan.FromSeconds(interval), TimeSpan.FromSeconds(interval));
                break;

            default:
            case ExtendedExecutionResult.Denied:
                this.NotifyUser("Extended execution denied.", NotifyType.ErrorMessage);
                newSession.Dispose();
                break;
            }
            //UpdateUI();
        }
 private static void StopCurrentSession()
 {
     if (session != null)
     {
         session.Dispose();
         session = null;
     }
 }
示例#20
0
 public void StopTracking()
 {
     if (_session != null)
     {
         _session.Dispose();
         _session = null;
     }
 }
示例#21
0
 private void StopLocationExtensionSession()
 {
     if (session != null)
     {
         session.Dispose();
         session = null;
     }
 }
 public MainPage()
 {
     this.InitializeComponent();
     loader  = ResourceLoader.GetForCurrentView("Resources");
     mp      = this;
     session = null;
     CheckLocalFolder();
 }
 private void ClearExecutionSession(ExtendedExecutionSession session)
 {
     if (session != null)
     {
         session.Revoked -= SessionRevoked;
         session.Dispose();
     }
 }
示例#24
0
文件: App.xaml.cs 项目: vargen2/Addon
 private void SessionRevoked(object sender, ExtendedExecutionRevokedEventArgs args)
 {
     if (_session != null)
     {
         _session.Dispose();
         _session = null;
     }
 }
        public async Task StartSyncProcess()
        {
            if (_pauseTokenSource?.IsPaused ?? false)
            {
                await ResumeAsync();

                return;
            }

            var run = true;

            if (!ChargerAndNetworkAvailable())
            {
                run = await GetWarningDialogResultAsync();
            }
            if (run)
            {
                await Task.Factory.StartNew(async() =>
                {
                    _executionSession             = await RequestExtendedExecutionAsync();
                    _pauseTokenSource             = new PauseTokenSource();
                    DisplayRequest displayRequest = null;
                    try
                    {
                        await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
                            CoreDispatcherPriority.Normal, () =>
                        {
                            displayRequest = new DisplayRequest();
                            displayRequest.RequestActive();
                        });
                        _Initialize();
                        await _worker.Run(_pauseTokenSource);
                    }
                    catch (Exception e)
                    {
                        if (Windows.ApplicationModel.Core.CoreApplication.Views.Count > 0)
                        {
                            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                            {
                                ExecutionContext.Instance.Status = ExecutionStatus.Error;
                            });
                        }
                        await LogHelper.Write(e.Message);
                        await LogHelper.Write(e.StackTrace);
                    }
                    finally
                    {
                        await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
                            CoreDispatcherPriority.Normal, () =>
                        {
                            displayRequest?.RequestRelease();
                            ExecutionContext.Instance.IsPaused = false;
                        });
                        ClearExecutionSession(_executionSession);
                    }
                });
            }
        }
        private async Task DownloadFilesAsync(List <DavItem> files)
        {
            FolderPicker picker = new FolderPicker();

            picker.FileTypeFilter.Add(".");
            picker.SuggestedStartLocation = PickerLocationId.Downloads;
            var folder = await picker.PickSingleFolderAsync();

            _tokenSource = new CancellationTokenSource();
            var button = new Button();

            button.Content             = App.ResourceLoader.GetString("Cancel");
            button.HorizontalAlignment = HorizontalAlignment.Center;
            button.Command             = new DelegateCommand(() =>
            {
                _tokenSource.Cancel(false);
                IndicatorService.GetDefault().HideBar();
            });
            _executionSession = await RequestExtendedExecutionAsync();

            try
            {
                foreach (var fileToDownload in files)
                {
                    if (_tokenSource.IsCancellationRequested)
                    {
                        IndicatorService.GetDefault().HideBar();
                        SelectionMode = ListViewSelectionMode.Single;
                        return;
                    }
                    var progress = new Progress <HttpProgress>(async httpProgress =>
                    {
                        if (_tokenSource.IsCancellationRequested)
                        {
                            return;
                        }
                        await Dispatcher.DispatchAsync(() =>
                        {
                            var text = string.Format(App.ResourceLoader.GetString("DownloadingFile"), fileToDownload.DisplayName);
                            text    += Environment.NewLine + new BytesToSuffixConverter().Convert(httpProgress.BytesReceived, null, null, null) + " - " + new ProgressToPercentConverter().Convert(httpProgress, null, null, null);
                            IndicatorService.GetDefault().ShowBar(text, button);
                        });
                        if (httpProgress.BytesReceived == httpProgress.TotalBytesToReceive && files.Count - 1 == files.IndexOf(fileToDownload))
                        {
                            IndicatorService.GetDefault().HideBar();
                            SelectionMode = ListViewSelectionMode.Single;
                        }
                    });
                    await WebDavItemService.GetDefault().DownloadAsync(fileToDownload, folder, _tokenSource.Token, progress);
                }
                _tokenSource.Cancel();
            }
            finally
            {
                ClearExecutionSession(_executionSession);
                IndicatorService.GetDefault().HideBar();
            }
        }
示例#27
0
 public void CancelExecutedExtension()
 {
     if (newSession != null)
     {
         newSession.Revoked -= NewSession_Revoked;
         newSession.Dispose();
         newSession = null;
     }
 }
 static void CreateInternal()
 {
     s_isStarted = s_isRevoked = false;
     s_extendedExecutionSession = new ExtendedExecutionSession
     {
         Description = typeof(ExtendedSessionManager).ToString(),
     };
     s_extendedExecutionSession.Revoked += HandleRevoked;
 }
示例#29
0
 void ClearExtendedExecution()
 {
     if (session != null)
     {
         session.Revoked -= SessionRevoked;
         session.Dispose();
         session = null;
     }
 }
 static void Create()
 {
     _isStarted = _isRevoked = false;
     _extendedExecutionSession = new ExtendedExecutionSession
     {
         Description = typeof(ExtendedSessionManager).ToString(),
     };
     _extendedExecutionSession.Revoked += _extendedExecutionSession_Revoked;
 }
示例#31
0
 private void ClearExtendedExecution()
 {
     if (_extendedExecutionSession != null)
     {
         _extendedExecutionSession.Revoked -= OnExtendedExecutionSessionRevoked;
         _extendedExecutionSession.Dispose();
         _extendedExecutionSession = null;
     }
 }
示例#32
0
        private async void BeginExtendedExecution()
        {
            var newSession = new ExtendedExecutionSession {
                Reason = ExtendedExecutionReason.Unspecified
            };

            session = newSession;
            _       = await session.RequestExtensionAsync();
        }
示例#33
0
 static void Create()
 {
     _isStarted = _isRevoked = false;
     _extendedExecutionSession?.Dispose();
     _extendedExecutionSession = new ExtendedExecutionSession
     {
         Description = typeof(ExtendedServiceHelper).ToString(),
     };
     _extendedExecutionSession.Revoked += (s, e) =>
     {
         _isStarted = false;
         _isRevoked = true;
     };
 }
        void ClearExtendedExecution()
        {
            if (session != null)
            {
                session.Revoked -= SessionRevoked;
                session.Dispose();
                session = null;
            }

            if (periodicTimer != null)
            {
                periodicTimer.Dispose();
                periodicTimer = null;
            }
        }
        private async void OnSuspending(object sender, SuspendingEventArgs args)
        {
            SuspendingDeferral suspendDeferral = args.SuspendingOperation.GetDeferral();

            rootPage.NotifyUser("", NotifyType.StatusMessage);

            using (var session = new ExtendedExecutionSession())
            {
                session.Reason = ExtendedExecutionReason.SavingData;
                session.Description = "Pretending to save data to slow storage.";
                session.Revoked += ExtendedExecutionSessionRevoked;

                ExtendedExecutionResult result = await session.RequestExtensionAsync();
                switch (result)
                {
                    case ExtendedExecutionResult.Allowed:
                        // We can perform a longer save operation (e.g., upload to the cloud).
                        try
                        {
                            MainPage.DisplayToast("Performing a long save operation.");
                            cancellationTokenSource = new CancellationTokenSource();
                            await Task.Delay(TimeSpan.FromSeconds(10), cancellationTokenSource.Token);
                            MainPage.DisplayToast("Still saving.");
                            await Task.Delay(TimeSpan.FromSeconds(10), cancellationTokenSource.Token);
                            MainPage.DisplayToast("Long save complete.");
                        }
                        catch (TaskCanceledException) { }
                        break;
                    default:
                    case ExtendedExecutionResult.Denied:
                        // We must perform a fast save operation.
                        MainPage.DisplayToast("Performing a fast save operation.");
                        await Task.Delay(TimeSpan.FromSeconds(1));
                        MainPage.DisplayToast("Fast save complete.");
                        break;
                }

                session.Revoked -= ExtendedExecutionSessionRevoked;
            }

            suspendDeferral.Complete();
        }
        void ClearExtendedExecution()
        {
            // Cancel any outstanding tasks.
            if (cancellationTokenSource != null)
            {
                // Save a copy of cancellationTokenSource because the call
                // to cancellationTokenSource.Cancel() will cause other code
                // to run, which might in turn call ClearExtendedExecution.
                var localCancellationTokenSource = cancellationTokenSource;
                cancellationTokenSource = null;

                localCancellationTokenSource.Cancel();
                localCancellationTokenSource.Dispose();
            }

            // Dispose any outstanding session.
            if (session != null)
            {
                session.Revoked -= SessionRevoked;
                session.Dispose();
                session = null;
            }
        }
示例#37
0
 private async void StartLocationExtensionSession()
 {
     session = new ExtendedExecutionSession();
     session.Description = "Location Tracker";
     session.Reason = ExtendedExecutionReason.LocationTracking;
     session.Revoked += Session_Revoked;
     var result = await session.RequestExtensionAsync();
     if (result == ExtendedExecutionResult.Denied)
     {
         //TODO: handle denied
     }
 }
示例#38
0
		/// <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)
		{
			MessageDialog m = new MessageDialog($"{(RequestExtension ? "" : "Not ")} Requesting Extension", "Suspending!");
			m.ShowAsync();

			Debug.WriteLine("Suspending...");
			DateTime now = DateTime.Now;
			LocalSettings.Values["Suspended"] = now.Ticks;

			var deferral = e.SuspendingOperation.GetDeferral();
			Debug.WriteLine($"Suspend Deadline: {e.SuspendingOperation.Deadline - now}");
			using (var extension = new ExtendedExecutionSession())
			{
				extension.Description = "Testing...";
				extension.Reason = ExtendedExecutionReason.SavingData;
				extension.Revoked += RevokedExtension;
				//var result = ExtendedExecutionResult.Denied;
				var result = RequestExtension ? await extension.RequestExtensionAsync() : ExtendedExecutionResult.Denied;
				Debug.WriteLine($"Suspend Deadline after Request: {e.SuspendingOperation.Deadline - now}");
				if (result == ExtendedExecutionResult.Allowed)
				{
					Debug.WriteLine("Granted Extended Execution");
					await DoWork(e.SuspendingOperation);
				}
				else
				{
					Debug.WriteLine("Denied Extended Execution");
					await DoWork(e.SuspendingOperation);
				}
			}
			Debug.WriteLine("Done.");
			deferral.Complete();
		}
示例#39
0
        /// <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();

            ToastHelper.ShowToast("App is suspending...");

            using (var session = new ExtendedExecutionSession())
            {
                session.Reason = ExtendedExecutionReason.SavingData;
                session.Description = "Uploading data to the cloud";
                session.Revoked += Session_Revoked;

                var result = await session.RequestExtensionAsync();

                await CacheHelper.SaveLocalData();

                if (result == ExtendedExecutionResult.Allowed)
                {
                    await CacheHelper.SaveCloudData();
                }
            }

            deferral.Complete();
        }
        private async void BeginExtendedExecution()
        {
            // The previous Extended Execution must be closed before a new one can be requested.
            // This code is redundant here because the sample doesn't allow a new extended
            // execution to begin until the previous one ends, but we leave it here for illustration.
            ClearExtendedExecution();

            var newSession = new ExtendedExecutionSession();
            newSession.Reason = ExtendedExecutionReason.Unspecified;
            newSession.Description = "Running multiple tasks";
            newSession.Revoked += SessionRevoked;
            ExtendedExecutionResult result = await newSession.RequestExtensionAsync();

            switch (result)
            {
                case ExtendedExecutionResult.Allowed:
                    rootPage.NotifyUser("Extended execution allowed.", NotifyType.StatusMessage);
                    session = newSession;
                    break;

                default:
                case ExtendedExecutionResult.Denied:
                    rootPage.NotifyUser("Extended execution denied.", NotifyType.ErrorMessage);
                    newSession.Dispose();
                    break;
            }
            UpdateUI();

            if (session != null)
            {
                cancellationTokenSource = new CancellationTokenSource();

                // Start up a few tasks that all share this session.
                using (var deferral = GetExecutionDeferral())
                {
                    var random = new Random();
                    for (int i = 0; i < 3; i++)
                    {
                        RaiseToastAfterDelay(i, random.Next(5, 10));
                    }
                }
            }
        }
示例#41
0
        private async Task CheckExtendedExecution()
        {
            if (AskForExtendedExecutionOnNextSuspend)
            {
                AskForExtendedExecutionOnNextSuspend = false;
                using (var session = new ExtendedExecutionSession()
                {
                    Reason = ExtendedExecutionReason.SavingData
                })
                {
                    session.Revoked += (s, args) =>
                    {
                        AppLog.Write("extended execution revoked, reason: " + args.Reason);
                    };
                    session.Description = "toasting things up";

                    var extendedExecutionResult = await session.RequestExtensionAsync();
                    if (extendedExecutionResult == ExtendedExecutionResult.Allowed)
                    {
                        while (true)
                        {
                            await Task.Delay(TimeSpan.FromSeconds(10));
                            ShowStillAliveToast();
                        }
                    }
                }
            }
        }
        private async void BeginExtendedExecution()
        {
            // The previous Extended Execution must be closed before a new one can be requested.
            // This code is redundant here because the sample doesn't allow a new extended
            // execution to begin until the previous one ends, but we leave it here for illustration.
            ClearExtendedExecution();

            var newSession = new ExtendedExecutionSession();
            newSession.Reason = ExtendedExecutionReason.LocationTracking;
            newSession.Description = "Tracking your location";
            newSession.Revoked += SessionRevoked;
            ExtendedExecutionResult result = await newSession.RequestExtensionAsync();

            switch (result)
            {
                case ExtendedExecutionResult.Allowed:
                    rootPage.NotifyUser("Extended execution allowed.", NotifyType.StatusMessage);
                    session = newSession;
                    Geolocator geolocator = await StartLocationTrackingAsync();
                    periodicTimer = new Timer(OnTimer, geolocator, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(10));
                    break;

                default:
                case ExtendedExecutionResult.Denied:
                    rootPage.NotifyUser("Extended execution denied.", NotifyType.ErrorMessage);
                    newSession.Dispose();
                    break;
            }
            UpdateUI();
        }
 private void ClearExtendedExecution()
 {
     if (session != null)
     {
         session.Revoked -= SessionRevoked;
         session.Dispose();
         session = null;
     }
 }
 public ExtendedExecutionSessionEvents(ExtendedExecutionSession This)
 {
     this.This = This;
 }
        private async Task BeginExtendedExecution()
        {
            if (ViewModel == null)
                return;

            ClearExtendedExecution();

            try
            {
                var newSession = new ExtendedExecutionSession
                {
                    Reason = ExtendedExecutionReason.LocationTracking,
                    Description = "Tracking your location"
                };
                newSession.Revoked += SessionRevoked;
                ExtendedExecutionResult result = await newSession.RequestExtensionAsync();
                switch (result)
                {
                    case ExtendedExecutionResult.Allowed:
                        session = newSession;
                        ViewModel.Geolocator.AllowsBackgroundUpdates = true;
                        ViewModel.StartTrackingTripCommand.Execute(null);

                        break;

                    default:
                        Acr.UserDialogs.UserDialogs.Instance.Alert("Unable to execute app in the background.",
                          "Background execution denied.", "OK");

                        newSession.Dispose();
                        break;
                }
            }
            catch (Exception ex)
            {
                // Sometimes while creating ExtendedExecution session you get Resource not ready exception. 
                Logger.Instance.Report(ex);
                Acr.UserDialogs.UserDialogs.Instance.Alert("Will not be able to execute app in the background.",
                        "Background execution session failed.", "OK");
            }
        }
示例#46
0
 private async Task<bool> AllowExtendedExecution()
 {
     using (var session = new ExtendedExecutionSession())
     {
         session.Reason = ExtendedExecutionReason.SavingData;
         session.Description = "uploading data";
         session.Revoked += Session_Revoked; ;
         var res = await session.RequestExtensionAsync();
         return res == ExtendedExecutionResult.Allowed;
     }
 }
    private async Task<bool> StartBackgroundSession()
    {
      if (_session != null)
      {
        try
        {
          _session.Dispose();
        }
        catch (Exception){}
      }
      _session = null;
      {
        _session = new ExtendedExecutionSession
        {
          Description = "Temperature tracking",
          Reason = ExtendedExecutionReason.LocationTracking
        };
        StartFakeGeoLocator();

        _session.Revoked += async (p, q) => { await OnRevoke(); };

        var result = await _session.RequestExtensionAsync();
        return result != ExtendedExecutionResult.Denied;
      }
      return false;
    }