Example #1
0
        public static async Task <bool> Start()
        {
            _session.Reason      = ExtendedExecutionReason.LocationTracking;
            _session.Description = "Serving requests";
            var result = await _session.RequestExtensionAsync();

            await Logger.Log($"Extended execution: {result}.");

            return(result == ExtendedExecutionResult.Allowed);
        }
        public async Task <bool> StartAsync(SessionKinds kind)
        {
            try
            {
                switch (kind)
                {
                case SessionKinds.Unspecified:
                    _extendedExecutionSession.Reason = ExtendedExecutionReason.Unspecified;
                    break;

                case SessionKinds.LocationTracking:
                    _extendedExecutionSession.Reason = ExtendedExecutionReason.LocationTracking;
                    break;

                case SessionKinds.SavingData:
                    _extendedExecutionSession.Reason = ExtendedExecutionReason.SavingData;
                    break;

                default:
                    throw new NotSupportedException(kind.ToString());
                }
                var result = await _extendedExecutionSession.RequestExtensionAsync();

                return(result == ExtendedExecutionResult.Allowed);
            }
            catch
            {
                return(false);
            }
        }
Example #3
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;
            }
        }
Example #4
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();
        }
Example #5
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;
            }
        }
Example #7
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;
            }
        }
Example #8
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();
        }
Example #9
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 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;
                    }
                }
            }));
        }
        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;
            }
        }
Example #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 { }
        }
        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;
            }
        }
Example #14
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();
        }
Example #15
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;
            }
        }
    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;
        }
    }
        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;
            }
        }
Example #18
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;
            }
        }
Example #19
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;
            }
        }
Example #20
0
        private async void BeginExtendedExecution()
        {
            var newSession = new ExtendedExecutionSession {
                Reason = ExtendedExecutionReason.Unspecified
            };

            session = newSession;
            _       = await session.RequestExtensionAsync();
        }
        /// <summary>
        /// Requests an extended session from the OS so as not to be suspended
        /// </summary>
        private void RequestExtendedSession()
        {
            _Session = new ExtendedExecutionSession();

            _Session.Reason      = ExtendedExecutionReason.Unspecified;
            _Session.Description = "Periodic check of the website";

            _Session.RequestExtensionAsync();
        }
Example #22
0
        private async void OnStartSync(CoreDispatcher dispatcher)
        {
            //#if DEBUG
            //await VoIPConnection.Current.ConnectAsync();
            //#endif

            await Toast.RegisterBackgroundTasks();

            try
            {
                TileUpdateManager.CreateTileUpdaterForApplication("App").Clear();
            }
            catch { }

            try
            {
                ToastNotificationManager.History.Clear("App");
            }
            catch { }

#if DESKTOP_BRIDGE
            if (ApiInformation.IsTypePresent("Windows.ApplicationModel.FullTrustProcessLauncher"))
            {
                try
                {
                    await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
                }
                catch
                {
                    // The app has been compiled without desktop bridge
                }
            }
#endif

            if (_extendedSession == null && ApiInfo.IsFullExperience)
            {
                var session = new ExtendedExecutionSession {
                    Reason = ExtendedExecutionReason.Unspecified
                };
                var result = await session.RequestExtensionAsync();

                if (result == ExtendedExecutionResult.Allowed)
                {
                    _extendedSession = session;

                    Logs.Logger.Info(Logs.Target.Lifecycle, "ExtendedExecutionResult.Allowed");
                }
                else
                {
                    session.Dispose();

                    Logs.Logger.Warning(Logs.Target.Lifecycle, "ExtendedExecutionResult.Denied");
                }
            }
        }
Example #23
0
        // アプリの再起動

        // How to Restart your App Programmatically - Windows Developer Blog (2017/07/28)
        // https://blogs.windows.com/buildingapps/2017/07/28/restart-app-programmatically/


        private async void RestartButton_Click(object sender, RoutedEventArgs e)
        {
            RestartButton.IsEnabled     = false;
            RestartDescriptionText.Text = "";

            using (var newSession = new ExtendedExecutionSession())
            {
                newSession.Reason = ExtendedExecutionReason.Unspecified;
                await newSession.RequestExtensionAsync();

                // ↑最小化されたときにサスペンドされるのを延期する(バックグラウンド実行)
                //   ※バッテリー駆動時は最大10分まで


                await Task.Delay(3000); // 動作確認のため、しばらく遅らせる

                // 再起動を要求する
                string param = App.RestartParamHeader + ParamText.Text;
                AppRestartFailureReason result = await CoreApplication.RequestRestartAsync(param);

                switch (result)
                {
                case AppRestartFailureReason.RestartPending:
                    // 正常に再起動処理が始まった
                    RestartDescriptionText.Text = "再起動中…";//この表示は見えない
                    break;

                case AppRestartFailureReason.NotInForeground:
                    // 失敗
                    RestartDescriptionText.Text
                        = "再起動失敗:アプリがフォアグラウンドになっていません。";
                    break;

                //case AppRestartFailureReason.InvalidUser:
                //  // 失敗(引数にユーザーを指定した場合に発生しうる)
                //  RestartDescriptionText.Text
                //    = "AppRestartFailureReason.InvalidUser";
                //  break;
                case AppRestartFailureReason.Other:
                    // 失敗
                    RestartDescriptionText.Text
                        = "再起動失敗:予期しない理由です。";
                    break;

#if DEBUG
                default:
                    throw new ArgumentOutOfRangeException($"想定外のAppRestartFailureReason({result})");
#endif
                }
            }

            RestartButton.IsEnabled = true;
        }
Example #24
0
        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();

            using (var session = new ExtendedExecutionSession())
            {
                session.Reason = ExtendedExecutionReason.SavingData;
                var requestTask = session.RequestExtensionAsync().AsTask();
                await Task.WhenAll(appControllers.Select(x => x.SuspendingAsync()).Concat(new[] { requestTask }).ToArray()).ConfigureAwait(false);
            }
            deferral.Complete();
        }
Example #25
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
            }
        }
Example #26
0
        async void ExtendExecutionAsync()
        {
            var extendedExecutionSession = new ExtendedExecutionSession();

            extendedExecutionSession.Reason = ExtendedExecutionReason.Unspecified;
            var extendedExecutionResult = await extendedExecutionSession.RequestExtensionAsync();

            if (extendedExecutionResult != ExtendedExecutionResult.Allowed)
            {
                //extended execution session revoked
                extendedExecutionSession.Dispose();
                extendedExecutionSession = null;
            }
        }
        private async Task <ExtendedExecutionSession> RequestExtendedExecutionAsync()
        {
            var session = new ExtendedExecutionSession();

            session.Reason   = ExtendedExecutionReason.Unspecified;
            session.Revoked += SessionRevoked;
            ExtendedExecutionResult result = await session.RequestExtensionAsync();

            if (result == ExtendedExecutionResult.Allowed)
            {
                return(session);
            }
            return(null);
        }
Example #28
0
        public static async Task <ExtendedExecutionController> TryCreateExtendedExecution()
        {
            await SlimLocker.WaitAsync();

            try
            {
                if (IsRequestExtensionSent)
                {
                    return(new ExtendedExecutionController());
                }
                else
                {
                    if (Session == null)
                    {
                        Session = new ExtendedExecutionSession
                        {
                            Reason = ExtendedExecutionReason.Unspecified
                        };

                        Session.Revoked += Session_Revoked;
                    }

                    switch (await Session.RequestExtensionAsync())
                    {
                    case ExtendedExecutionResult.Allowed:
                    {
                        IsRequestExtensionSent = true;
                        return(new ExtendedExecutionController());
                    }

                    default:
                    {
                        IsRequestExtensionSent = false;
                        LogTracer.Log("Extension execution was rejected by system");
                        return(null);
                    }
                    }
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, "An exception was threw when creating the extended execution");
                IsRequestExtensionSent = false;
                return(null);
            }
            finally
            {
                SlimLocker.Release();
            }
        }
        private async Task SetupExtendedSessionAsync()
        {
            var session = new ExtendedExecutionSession
            {
                Reason      = ExtendedExecutionReason.Unspecified,
                Description = "Fewer suspensions"
            };
            var result = await session.RequestExtensionAsync();

            if (result == ExtendedExecutionResult.Denied)
            {
                // do nothing
            }
        }
Example #30
0
        private async void StartLocationExtensionSession()
        {
            StopLocationExtensionSession();
            session             = new ExtendedExecutionSession();
            session.Description = "LocationTracking";
            session.Reason      = ExtendedExecutionReason.LocationTracking;
            session.Revoked    += Session_Revoked;
            var result = await session.RequestExtensionAsync();

            //if (result==ExtendedExecutionResult.Allowed)
            //{

            //}
        }
        private async void OnSuspending(object sender, SuspendingEventArgs args)
        {
            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();
            suspendDeferral = null;
        }
Example #32
0
        async private Task PreventSuspend()
        {
            ExtendedExecutionSession newSession = new ExtendedExecutionSession
            {
                Reason = ExtendedExecutionReason.Unspecified
            };

            ExtendedExecutionResult result = await newSession.RequestExtensionAsync();

            if (result != ExtendedExecutionResult.Allowed)
            {
                throw new Exception("ExtendedExecution not allowed");
            }

            session = newSession;
        }
        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();
        }
        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));
                    }
                }
            }
        }
Example #35
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
     }
 }
        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");
            }
        }
Example #37
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();
        }
		/// <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();
		}
Example #40
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;
    }
Example #42
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();
        }