Example #1
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 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;
            }
        }
        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 #4
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 #5
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;
            }
        }
        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 #7
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 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;
                    }
                }
            }));
        }
Example #9
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 { }
        }
Example #10
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();
        }
    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;
        }
    }
Example #12
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;
            }
        }
        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);
        }
        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 #15
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;
        }
Example #16
0
        private static async Task CreateOrClearExtendedExecutionSessionBasedOnCountDirect()
        {
            bool createNew = false;
            ExtendedExecutionSession localExtendedExecutionSession = null;

            lock (lockObject) {
                localExtendedExecutionSession = extendedExecutionSession;
                if (extendedExecutionRequestCount > 0)
                {
                    createNew = true;
                }
                else
                {
                    createNew = false;
                }
            }
            if (createNew && localExtendedExecutionSession == null)
            {
                var newSession = new ExtendedExecutionSession()
                {
                    Reason = ExtendedExecutionReason.Unspecified
                };
                newSession.Revoked += ExtendedExecutionSessionRevoked;
                ExtendedExecutionResult result = await newSession.RequestExtensionAsync();

                if (result == ExtendedExecutionResult.Allowed)
                {
                    lock (lockObject) {
                        extendedExecutionSession = newSession;
                    }
                }
                else
                {
                    newSession.Dispose();
                }
            }
            else if (localExtendedExecutionSession != null)
            {
                localExtendedExecutionSession.Revoked -= ExtendedExecutionSessionRevoked;
                localExtendedExecutionSession.Dispose();
                lock (lockObject) {
                    extendedExecutionSession = null;
                }
            }
        }
Example #17
0
        /// <summary>
        /// 在应用程序由最终用户正常启动时进行调用。
        /// 将在启动应用程序以打开特定文件等情况下使用。
        /// </summary>
        /// <param name="e">有关启动请求和过程的详细信息。</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs 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.PrelaunchActivated == false)
            {
                if (rootFrame.Content == null)
                {
                    // 当导航堆栈尚未还原时,导航到第一页,
                    // 并通过将所需信息作为导航参数传入来配置
                    // 参数
                    rootFrame.Navigate(typeof(MainPage), e.Arguments);
                }
                // 确保当前窗口处于活动状态
                Window.Current.Activate();

                Window.Current.Content = rootFrame;
            }

            var session = new ExtendedExecutionSession
            {
                Reason = ExtendedExecutionReason.Unspecified
            };

            session.Revoked += Session_Revoked;
            ExtendedExecutionResult result = await session.RequestExtensionAsync();
        }
        private async void BeginPusherEventReceptionSession()
        {
            // 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.
            EndPusherEventReceptionSession();

            var newSession = new ExtendedExecutionSession();

            newSession.Reason      = ExtendedExecutionReason.Unspecified;
            newSession.Description = "Checking for Pusher events";
            newSession.Revoked    += PusherEventReceptionSessionRevoked;
            ExtendedExecutionResult result = await newSession.RequestExtensionAsync();

            switch (result)
            {
            case ExtendedExecutionResult.Allowed:
                Debug.WriteLine("Extended execution was allowed");
                foreach (PusherEventConfig config in EventConfigs)
                {
                    var pusher = new Pusher(config.AppKey, new PusherOptions()
                    {
                        Cluster = config.AppCluster
                    });
                    pusher.ConnectionStateChanged += PusherConnectionStateChanged;
                    pusher.Error += PusherError;
                    ConnectionState connectionState = await pusher.ConnectAsync();

                    Channel myChannel = await pusher.SubscribeAsync(config.ChannelName);

                    myChannel.Bind(config.EventName, async(PusherClient.PusherEvent eventData) =>
                    {
                        await OnPusherEventReceptionAsync(config, eventData);
                    });
                }
                pusherEventReceptionSession = newSession;
                break;

            default:
            case ExtendedExecutionResult.Denied:
                Debug.WriteLine("Extended execution was denied");
                newSession.Dispose();
                break;
            }
        }
Example #19
0
        public static async void RequestExtension()
        {
            if (extendedExecutionSession == null)
            {
                extendedExecutionSession             = new ExtendedExecutionSession();
                extendedExecutionSession.Description = LocalizableStrings.EXTENDED_EXECUTION_DESCRIPTION;
                extendedExecutionSession.Reason      = ExtendedExecutionReason.Unspecified;
                extendedExecutionSession.Revoked    += ExtendedExecutionSession_Revoked;
            }
            ExtendedExecutionResult result = await extendedExecutionSession.RequestExtensionAsync();

            IsExtensionEnabled = (result == ExtendedExecutionResult.Allowed);

            if (IsExtensionEnabled)
            {
                MemoryManager.AppMemoryUsageLimitChanging += MemoryManager_AppMemoryUsageLimitChanging;
            }
        }
        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));
                    }
                }
            }
        }
        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 #22
0
        //
        // https://blogs.msdn.microsoft.com/mvpawardprogram/2018/01/30/non-suspending-uwp-desktop-apps/#comment-130715
        //
        private async Task PreventFromSuspending()
        {
            var newSession = new ExtendedExecutionSession();

            newSession.Reason   = ExtendedExecutionReason.Unspecified;
            newSession.Revoked += SessionRevoked;

            ExtendedExecutionResult result = await newSession.RequestExtensionAsync();

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

            default:
            case ExtendedExecutionResult.Denied:
                newSession.Dispose();
                break;
            }
        }
Example #23
0
        private async Task Recording()
        {
            switch (RecordStatus)
            {
            case ActivityTracking.Idle:
                //The previous Extended Execution must be closed before a new one can be requested
                //TODO: Glenn - we normally have to call this clear method when navigating away from the screen!
                ClearExtendedExecution();
                ExtendedExecutionSession newSession = new ExtendedExecutionSession
                {
                    Reason      = ExtendedExecutionReason.LocationTracking,
                    Description = "Kliva - location tracking"
                };

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

                switch (result)
                {
                case ExtendedExecutionResult.Allowed:
                    //TODO: Glenn - start location tracking!
                    RecordStatus = ActivityTracking.Recording;
                    _extendedExecutionSession = newSession;
                    await _gpxService.InitGPXDocument();

                    _periodicTimer = new Timer(OnTimer, _locationService, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2.2));
                    break;

                default:
                case ExtendedExecutionResult.Denied:
                    newSession.Dispose();
                    break;
                }
                break;

            case ActivityTracking.Recording:
                RecordStatus = ActivityTracking.Paused;
                break;
            }
        }
Example #24
0
        private async void doWorkButton_Click(object sender, RoutedEventArgs e)
        {
            // The previous Extended Execution must be closed before a new one can be requested.
            //ClearSession();

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

            switch (result)
            {
            case ExtendedExecutionResult.Allowed:
                strExtendedExecutionResult.Text = "ExtendedExecutionResult.Allowed";
                break;

            case ExtendedExecutionResult.Denied:
                strExtendedExecutionResult.Text = "ExtendedExecutionResult.Denied";
                break;
            }
            periodicTimer = new Timer(OnTimer, DateTime.Now, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(20));
        }
Example #25
0
        public async Task StartExtended()
        {
            ClearExtendedExecution();

            var newSession = new ExtendedExecutionSession();

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

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

            default:
            case ExtendedExecutionResult.Denied:
                newSession.Dispose();
                break;
            }
        }
Example #26
0
        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            SuspendingDeferral deferral = e.SuspendingOperation.GetDeferral();
            var newSession = new ExtendedExecutionSession
            {
                Reason = ExtendedExecutionReason.SavingData
            };

            newSession.Revoked += NewSession_Revoked;

            ExtendedExecutionResult result = await newSession.RequestExtensionAsync();

            if (result == ExtendedExecutionResult.Allowed)
            {
                await SharedState.LogAsync("Scannit: SUSPENDING!");

                await SharedState.SetAsync(SharedState.IsApplicationInForeground, false);

                newSession.Revoked -= NewSession_Revoked;
                newSession.Dispose();
                newSession = null;
            }
            deferral.Complete();
        }
        public static async Task <ExtendedExecutionResult> RequestExtendedSessionAsync()
        {
            StopCurrentSession();
            var newSession = new ExtendedExecutionSession();

            newSession.Reason      = ExtendedExecutionReason.Unspecified;
            newSession.Description = "for background voice recognition and alarm/reminder tracking";
            newSession.Revoked    += (sender, args) => StopCurrentSession();

            // ask for permission for extended execution
            ExtendedExecutionResult result = await newSession.RequestExtensionAsync();

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

            case ExtendedExecutionResult.Denied:
                newSession.Dispose();
                break;
            }
            return(result);
        }
 /// <summary>
 /// Logs result of extension request.
 /// </summary>
 /// <param name="result">The result to log.</param>
 public static void ExtensionRequestResult(ExtendedExecutionResult result)
 {
     EventLog.Log.Info($"Extension request returned result {result}");
 }
        private async void App_SuspendingAsync(object sender, SuspendingEventArgs args)
        {
            try
            {
                suspendDeferral = args.SuspendingOperation.GetDeferral();

                //DateTimeOffset deadline = args.SuspendingOperation.Deadline;
                _logHelper.Log(LogLevel.Trace, $"Entered App_SuspendingAsync.");

                using (var session = new ExtendedExecutionSession())
                {
                    session.Reason      = ExtendedExecutionReason.SavingData;
                    session.Description = "Saving application state.";
                    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
                        {
                            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
                            await localFolder.SaveAsync(PropertiesDictionaryFileName, Properties);

                            await MainViewModel.Instance.UpdateDownloadedBulletinsAsync();
                        }
                        catch (TaskCanceledException te)
                        {
                            _logHelper.Log(LogLevel.Trace, $"Extended Execution Error. {te.Message}");
                        }
                        break;

                    default:
                    case ExtendedExecutionResult.Denied:
                        // We must perform a fast save operation.
                        _logHelper.Log(LogLevel.Trace, $"Extended Execution denied");
                        //MainPage.DisplayToast("Performing a fast save operation.");
                        //await Task.Delay(TimeSpan.FromSeconds(1));
                        //MainPage.DisplayToast("Fast save complete.");
                        break;
                    }

                    session.Revoked -= ExtendedExecutionSessionRevoked;
                }

                //StorageFolder localFolder = ApplicationData.Current.LocalFolder;
                //await localFolder.SaveAsync(PropertiesDictionaryFileName, Properties);

                //await Singleton<SuspendAndResumeService>.Instance.SaveStateAsync();

                //await MainViewModel.Instance.UpdateDownloadedBulletinsAsync();
            }
            catch (Exception e)
            {
                _logHelper.Log(LogLevel.Error, $"App_SuspendingAsync exception. {e.Message}");
            }
            finally
            {
                suspendDeferral?.Complete();
                suspendDeferral = null;
            }
        }
Example #30
0
        /// <summary>
        /// Wywoływane, gdy wykonanie aplikacji jest wstrzymywane. Stan aplikacji jest zapisywany
        /// bez wiedzy o tym, czy aplikacja zostanie zakończona, czy wznowiona z niezmienioną zawartością
        /// pamięci.
        /// </summary>
        /// <param name="sender">Źródło żądania wstrzymania.</param>
        /// <param name="e">Szczegóły żądania wstrzymania.</param>
        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();

            // To save all data,  extra time is needed, that's why ExtendedExecutionSession is used. On deny almost no data is saved.
            using (var session = new ExtendedExecutionSession())
            {
                session.Reason      = ExtendedExecutionReason.SavingData;
                session.Description = "Pretending to save data to slow storage.";
                ExtendedExecutionResult result = await session.RequestExtensionAsync();

                switch (result)
                {
                case ExtendedExecutionResult.Allowed:
                    Debug.WriteLine("Saving state");
                    StorageFile datesFile = await localFolder.CreateFileAsync("dates.txt",
                                                                              CreationCollisionOption.ReplaceExisting);

                    await FileIO.WriteTextAsync(datesFile, JsonConvert.SerializeObject(ViewModel.Dates));

                    StorageFile ratesFile = await localFolder.CreateFileAsync("rates.txt",
                                                                              CreationCollisionOption.ReplaceExisting);

                    await FileIO.WriteTextAsync(ratesFile, JsonConvert.SerializeObject(ViewModel.Rates));

                    composite["currentDate"]          = ViewModel.CurrentDate;
                    composite["currentDateSelection"] = ViewModel.CurrentDateSelection;
                    if (rootFrame.SourcePageType.Name == "RateHistory")
                    {
                        composite["currentCurrencyCode"] = ViewModel.CurrentCurrencyCode;
                        composite["toRateHistoryDate"]   = ViewModel.ToRateHistoryDate;
                        composite["fromRateHistoryDate"] = ViewModel.FromRateHistoryDate;
                        StorageFile historyFile = await localFolder.CreateFileAsync("history.txt",
                                                                                    CreationCollisionOption.ReplaceExisting);

                        await FileIO.WriteTextAsync(historyFile, JsonConvert.SerializeObject(ViewModel.HistoryOfCurrency));
                    }
                    else
                    {
                        composite["currentCurrencyCode"] = null;
                        composite["toRateHistoryDate"]   = null;
                        composite["fromRateHistoryDate"] = null;
                    }
                    composite["currentPage"] = rootFrame.GetNavigationState();
                    localSettings.Values["DataStoreViewModel"] = composite;
                    break;

                default:
                case ExtendedExecutionResult.Denied:
                    Debug.WriteLine("Can't save the whole state");
                    if (rootFrame.SourcePageType.Name == "RateHistory")
                    {
                        composite["toRateHistoryDate"]   = ViewModel.ToRateHistoryDate;
                        composite["fromRateHistoryDate"] = ViewModel.FromRateHistoryDate;
                        composite["currentCurrencyCode"] = ViewModel.CurrentCurrencyCode;
                    }
                    else
                    {
                        composite["currentCurrencyCode"] = null;
                        composite["toRateHistoryDate"]   = null;
                        composite["fromRateHistoryDate"] = null;
                    }
                    composite["currentDate"]                   = null;;
                    composite["currentDateSelection"]          = null;;
                    composite["currentPage"]                   = rootFrame.GetNavigationState();
                    localSettings.Values["DataStoreViewModel"] = composite;
                    break;
                }
            }
            deferral.Complete();
        }