/// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        ///
        /// We will enable/disable parts of the UI if the device doesn't support it.
        /// </summary>
        /// <param name="eventArgs">Event data that describes how this page was reached. The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;

            // Get the existing task if already registered
            if (taskRegistration == null)
            {
                // Find the task if we previously registered it
                foreach (var task in BackgroundTaskRegistration.AllTasks.Values)
                {
                    if (task.Name == taskName)
                    {
                        taskRegistration = task;
                        taskRegistration.Completed += OnBackgroundTaskCompleted;
                        break;
                    }
                }
            }
            else
                taskRegistration.Completed += OnBackgroundTaskCompleted;

            // Attach handlers for suspension to stop the watcher when the App is suspended.
            App.Current.Suspending += App_Suspending;
            App.Current.Resuming += App_Resuming;

            rootPage.NotifyUser("Press Run to register watcher.", NotifyType.StatusMessage);
        }
    public void StartLocationTracker()
    {
     if( CanRunAsTask() )
      {
        BackgroundTaskBuilder geolocTaskBuilder = new BackgroundTaskBuilder();

        geolocTaskBuilder.Name = SampleBackgroundTaskName;
        geolocTaskBuilder.TaskEntryPoint = SampleBackgroundTaskEntryPoint;

        // Create a new timer triggering at a 15 minute interval
        var trigger = new TimeTrigger( UpdateInterval, true );

        // Associate the timer trigger with the background task builder
        geolocTaskBuilder.SetTrigger( trigger );

        // Register the background task
        _geolocTask = geolocTaskBuilder.Register();

        // Associate an event handler with the new background task
        _geolocTask.Completed += new BackgroundTaskCompletedEventHandler( OnCompleted );
      }
      else
      {
         task = new LocationBackgroundTask();
        timer = ThreadPoolTimer.CreatePeriodicTimer( TimerElapsed, new TimeSpan( TimeSpan.TicksPerMillisecond * 30000 ) );
     }
    }
 private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
 {
     ShellToast toast = new ShellToast();
     toast.Title = "Sample Application";
     toast.Content = "Background Task Complete";
     toast.Show();
 }
 void UnregisterTask()
 {
     this.taskRegistration.Completed -= OnCompleted;
     this.taskRegistration.Progress -= OnProgress;
     this.taskRegistration.Unregister(false);
     this.taskRegistration = null;
     BackgroundExecutionManager.RemoveAccess();
 }
 public void StopLocationTracker()
 {
   if( null != _geolocTask )
   {
     _geolocTask.Unregister( true );
     _geolocTask = null;
   }
 }
		private async Task<Tuple<bool, string>> TryRegisterUploadToOneDriveBackgroundTaskAsync()
		{
			bool isOk = false;
			string msg = string.Empty;

			string errorMsg = string.Empty;
			BackgroundAccessStatus backgroundAccessStatus = BackgroundAccessStatus.Unspecified;

			_uploadToOneDriveBkgTaskReg = null;
			UnregisterTaskIfAlreadyRegistered(); // I need to unregister and register anew coz I need to obtain the trigger

			try
			{
				// Get permission for a background task from the user. If the user has already answered once,
				// this does nothing and the user must manually update their preference via PC Settings.
				Task<BackgroundAccessStatus> requestAccess = null;
				await RunInUiThreadIdleAsync(() => requestAccess = BackgroundExecutionManager.RequestAccessAsync().AsTask()).ConfigureAwait(false);
				backgroundAccessStatus = await requestAccess.ConfigureAwait(false);

				// Regardless of the answer, register the background task. If the user later adds this application
				// to the lock screen, the background task will be ready to run.
				// Create a new background task builder
				BackgroundTaskBuilder bkgTaskBuilder = new BackgroundTaskBuilder
				{
					Name = ConstantData.ODU_BACKGROUND_TASK_NAME,
					TaskEntryPoint = ConstantData.ODU_BACKGROUND_TASK_ENTRY_POINT
				};

				_uploadToOneDriveTrigger = new ApplicationTrigger();
				bkgTaskBuilder.SetTrigger(_uploadToOneDriveTrigger);
				// bkgTaskBuilder.AddCondition(new SystemCondition(SystemConditionType.SessionDisconnected)); // NO!
				// Register the background task
				_uploadToOneDriveBkgTaskReg = bkgTaskBuilder.Register();
			}
			catch (Exception ex)
			{
				errorMsg = ex.ToString();
				backgroundAccessStatus = BackgroundAccessStatus.Denied;
				Logger.Add_TPL(ex.ToString(), Logger.ForegroundLogFilename);
			}

			switch (backgroundAccessStatus)
			{
				case BackgroundAccessStatus.Unspecified:
					msg = "Cannot run in background, enable it in the \"Battery Saver\" app";
					break;
				case BackgroundAccessStatus.Denied:
					msg = string.IsNullOrWhiteSpace(errorMsg) ? "Cannot run in background, enable it in Settings - Privacy - Background apps" : errorMsg;
					break;
				default:
					msg = "Background task on";
					isOk = true;
					break;
			}

			return Tuple.Create(isOk, msg);
		}
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached. The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Loop through all background tasks to see if SampleBackgroundTaskName is already registered
            foreach (var cur in BackgroundTaskRegistration.AllTasks)
            {
                if (cur.Value.Name == SampleBackgroundTaskName)
                {
                    _geolocTask = cur.Value;
                    break;
                }
            }

            if (_geolocTask != null)
            {
                // Associate an event handler with the existing background task
                _geolocTask.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);

                try
                {
                    BackgroundAccessStatus backgroundAccessStatus = BackgroundExecutionManager.GetAccessStatus();

                    switch (backgroundAccessStatus)
                    {
                        case BackgroundAccessStatus.Unspecified:
                        case BackgroundAccessStatus.Denied:
                            rootPage.NotifyUser("This application must be added to the lock screen before the background task will run.", NotifyType.ErrorMessage);
                            break;

                        default:
                            rootPage.NotifyUser("Background task is already registered. Waiting for next update...", NotifyType.ErrorMessage);
                            break;
                    }
                }
                catch (Exception ex)
                {
                    // HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED) == 0x80070032
                    const int RequestNotSupportedHResult = unchecked((int)0x80070032);

                    if (ex.HResult == RequestNotSupportedHResult)
                    {
                        rootPage.NotifyUser("Location Simulator not supported.  Could not determine lock screen status, be sure that the application is added to the lock screen.", NotifyType.StatusMessage);
                    }
                    else
                    {
                        rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
                    }
                }

                UpdateButtonStates(/*registered:*/ true);
            }
            else
            {
                UpdateButtonStates(/*registered:*/ false);
            }
        }
        public MainPage()
        {
            this.InitializeComponent();
            
            beacons = new ObservableCollection<iBeaconData>();
            this.DataContext = beacons;

            //Unregister the old task
            var taskAdvertisementWatcher = BackgroundTaskRegistration.AllTasks.Values.Where(t => t.Name == taskName).FirstOrDefault();
            if (taskAdvertisementWatcher != null)
            {
                taskAdvertisementWatcher.Unregister(true);
                taskAdvertisementWatcher = null;
                Button_Click(null, null);
            }
        }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached. The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Loop through all background tasks to see if SampleGeofenceBackgroundTask is already registered
            foreach (var cur in BackgroundTaskRegistration.AllTasks)
            {
                if (cur.Value.Name == SampleBackgroundTaskName)
                {
                    _geofenceTask = cur.Value;
                    break;
                }
            }

            if (_geofenceTask != null)
            {
                FillEventListBoxWithExistingEvents();

                // Associate an event handler with the existing background task
                _geofenceTask.Completed += OnCompleted;

                try
                {
                    BackgroundAccessStatus backgroundAccessStatus = BackgroundExecutionManager.GetAccessStatus();
                    switch (backgroundAccessStatus)
                    {
                        case BackgroundAccessStatus.Unspecified:
                        case BackgroundAccessStatus.Denied:
                            _rootPage.NotifyUser("Not able to run in background. Application must be added to the lock screen.", NotifyType.ErrorMessage);
                            break;

                        default:
                            _rootPage.NotifyUser("Background task is already registered. Waiting for next update...", NotifyType.StatusMessage);
                            break;
                    }
                }
                catch (Exception ex)
                {
                    _rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
                }
                UpdateButtonStates(/*registered:*/ true);
            }
            else
            {
                UpdateButtonStates(/*registered:*/ false);
            }
        }
Beispiel #10
0
        void UpdateTask()
        {
            lock (lockable)
            {
                var task = FindTask();

                if (task == backgroundTaskRegistration)
                    return;

                if (backgroundTaskRegistration != null)
                    backgroundTaskRegistration.Completed -= OnCompleted;

                backgroundTaskRegistration = task;

                if (backgroundTaskRegistration != null)
                    backgroundTaskRegistration.Completed += OnCompleted;
            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;
            try
            {
                foreach (var current in BackgroundTaskRegistration.AllTasks)
                {
                    if (current.Value.Name == "SocketActivityBackgroundTask")
                    {
                        task = current.Value;
                        break;
                    }
                }

                // If there is no task allready created, create a new one
                if (task == null)
                {
                    var socketTaskBuilder = new BackgroundTaskBuilder();
                    socketTaskBuilder.Name = "SocketActivityBackgroundTask";
                    socketTaskBuilder.TaskEntryPoint = "SocketActivityBackgroundTask.SocketActivityTask";
                    var trigger = new SocketActivityTrigger();
                    socketTaskBuilder.SetTrigger(trigger);
                    task = socketTaskBuilder.Register();
                }

                SocketActivityInformation socketInformation;
                if (SocketActivityInformation.AllSockets.TryGetValue(socketId, out socketInformation))
                {
                    // Application can take ownership of the socket and make any socket operation
                    // For sample it is just transfering it back.
                    socket = socketInformation.StreamSocket;
                    socket.TransferOwnership(socketId);
                    socket = null;
                    rootPage.NotifyUser("Connected. You may close the application", NotifyType.StatusMessage);
                    TargetServerTextBox.IsEnabled = false;
                    ConnectButton.IsEnabled = false;
                }

            }
            catch (Exception exception)
            {
                rootPage.NotifyUser(exception.Message, NotifyType.ErrorMessage);
            }
        }
        private void SetupBackGroundTask()
        {
            foreach(var task in BackgroundTaskRegistration.AllTasks)
            {
                if(task.Value.Name == BackgroundTaskName)
                {
                    regTask = task.Value;
                }
            }

            if(regTask != null)
            {
                regTask.Completed += RegTask_Completed;
            }

            else
            {
                RegisterTask();
            }
        }
 protected override async void OnNavigatedTo(NavigationEventArgs e)
 {
     var registration = BackgroundTaskRegistration.AllTasks.FirstOrDefault(x => x.Value.Name == TaskName);
     if (registration.Value == null)
     {
         var socketTaskBuilder = new BackgroundTaskBuilder();
         socketTaskBuilder.Name = TaskName;
         socketTaskBuilder.TaskEntryPoint = "SocketTask.ReceiveMessagesTask";
         var trigger = new SocketActivityTrigger();
         socketTaskBuilder.SetTrigger(trigger);
         var status = await BackgroundExecutionManager.RequestAccessAsync();
         if (status != BackgroundAccessStatus.Denied)
         {
             task = socketTaskBuilder.Register();
         }
     }
     else
     {
         task = registration.Value;
     }
 }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;

            selectorComboBox.ItemsSource = DeviceSelectorChoices.BackgroundDeviceWatcherSelectors;
            selectorComboBox.SelectedIndex = 0;

            DataContext = this;

            // Determine if the background task is already active
            foreach (var task in BackgroundTaskRegistration.AllTasks)
            {
                if (backgroundTaskName == task.Value.Name)
                {
                    backgroundTaskRegistration = task.Value;
                    startWatcherButton.IsEnabled = false;
                    stopWatcherButton.IsEnabled = true;
                    break;
                }
            }
        }
        public async Task RegisterBackgroundTask(string bgWorkerTaskName, string bgWorkerTaskEntryPoint)
        {
            foreach (var task in BackgroundTaskRegistration.AllTasks)
            {
                if (task.Value.Name == bgWorkerTaskName)
                {
                    bgWorkerTaskRegistration = task.Value;
                    break;
                }
            }

            if (bgWorkerTaskRegistration != null)
            {
                //statusTextBlock.Text = "STATUS: Background worker already registered.";
                return;
            }
            else
            {
                BackgroundAccessStatus bgAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

                var builder = new BackgroundTaskBuilder();
                builder.TaskEntryPoint = bgWorkerTaskEntryPoint;
                builder.SetTrigger(new TimeTrigger(30, false));
                builder.Name = bgWorkerTaskName;

                try
                {
                    bgWorkerTaskRegistration = builder.Register();
                    //statusTextBlock.Text = "STATUS: BG Worker Registered";
                }
                catch (Exception)
                {

                    throw;
                }
            }
        }
 /// <summary>
 /// Handle background task progress.
 /// </summary>
 /// <param name="task">The task that is reporting progress.</param>
 /// <param name="e">Arguments of the progress report.</param>
 private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
 {
     var progress = "Progress: " + args.Progress + "%";
     BackgroundTaskSample.SampleBackgroundTaskWithConditionProgress = progress;
     UpdateUI();
 }
 private void UnregisterBackgroundTask(IBackgroundTaskRegistration taskReg)
 {
     taskReg.Unregister(true);
     ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
     settings.Values["eventCount"] = (uint)0;
 }
        /// <summary>
        /// Handle background task completion.
        /// </summary>
        /// <param name="task">The task that is reporting completion.</param>
        /// <param name="e">Arguments of the completion report.</param>
        private async void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
        {
            ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;

            Object profile = localSettings.Values["InternetProfile"];
            Object adapter = localSettings.Values["NetworkAdapterId"];

            Object hasNewConnectionCost = localSettings.Values["HasNewConnectionCost"];
            Object hasNewDomainConnectivityLevel = localSettings.Values["HasNewDomainConnectivityLevel"];
            Object hasNewHostNameList = localSettings.Values["HasNewHostNameList"];
            Object hasNewInternetConnectionProfile = localSettings.Values["HasNewInternetConnectionProfile"];
            Object hasNewNetworkConnectivityLevel = localSettings.Values["HasNewNetworkConnectivityLevel"];

            await NetworkStatusWithInternetPresentDispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                string outputText = string.Empty;

                if ((profile != null) && (adapter != null))
                {
                    //If internet profile has changed, display the new internet profile
                    if ((string.Equals(profile.ToString(), internetProfile, StringComparison.Ordinal) == false) ||
                            (string.Equals(adapter.ToString(), networkAdapter, StringComparison.Ordinal) == false))
                    {
                        internetProfile = profile.ToString();
                        networkAdapter = adapter.ToString();
                        outputText += "Internet Profile changed\n" + "=================\n" + "Current Internet Profile : " + internetProfile + "\n\n";

                        if (hasNewConnectionCost != null)
                        {
                            outputText += hasNewConnectionCost.ToString() + "\n";
                        }
                        if (hasNewDomainConnectivityLevel != null)
                        {
                            outputText += hasNewDomainConnectivityLevel.ToString() + "\n";
                        }
                        if (hasNewHostNameList != null)
                        {
                            outputText += hasNewHostNameList.ToString() + "\n";
                        }
                        if (hasNewInternetConnectionProfile != null)
                        {
                            outputText += hasNewInternetConnectionProfile.ToString() + "\n";
                        }
                        if (hasNewNetworkConnectivityLevel != null)
                        {
                            outputText += hasNewNetworkConnectivityLevel.ToString() + "\n";
                        }

                        rootPage.NotifyUser(outputText, NotifyType.StatusMessage);
                    }
                }
            });
        }
Beispiel #19
0
        /// <summary>
        /// This is the click handler for the 'Register' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void RegisterBackgroundTask(object sender, RoutedEventArgs e)
        {
            try
            {
                // Get permission for a background task from the user. If the user has already answered once,
                // this does nothing and the user must manually update their preference via PC Settings.
                BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

                // Regardless of the answer, register the background task. If the user later adds this application
                // to the lock screen, the background task will be ready to run.
                // Create a new background task builder
                BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder();

                geofenceTaskBuilder.Name           = SampleBackgroundTaskName;
                geofenceTaskBuilder.TaskEntryPoint = SampleBackgroundTaskEntryPoint;

                // Create a new location trigger
                var trigger = new LocationTrigger(LocationTriggerType.Geofence);

                // Associate the locationi trigger with the background task builder
                geofenceTaskBuilder.SetTrigger(trigger);

                // If it is important that there is user presence and/or
                // internet connection when OnCompleted is called
                // the following could be called before calling Register()
                // SystemCondition condition = new SystemCondition(SystemConditionType.UserPresent | SystemConditionType.InternetAvailable);
                // geofenceTaskBuilder.AddCondition(condition);

                // Register the background task
                _geofenceTask = geofenceTaskBuilder.Register();

                // Associate an event handler with the new background task
                _geofenceTask.Completed += OnCompleted;

                UpdateButtonStates(/*registered:*/ true);

                switch (backgroundAccessStatus)
                {
                case BackgroundAccessStatus.Unspecified:
                case BackgroundAccessStatus.Denied:
                    _rootPage.NotifyUser("Not able to run in background. Application must be added to the lock screen.",
                                         NotifyType.ErrorMessage);
                    break;

                default:
                    // BckgroundTask is allowed
                    _rootPage.NotifyUser("Geofence background task registered.", NotifyType.StatusMessage);

                    // Need to request access to location
                    // This must be done with the background task registeration
                    // because the background task cannot display UI.
                    RequestLocationAccess();
                    break;
                }
            }
            catch (Exception ex)
            {
                _rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
                UpdateButtonStates(/*registered:*/ false);
            }
        }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            IHttpFilter filter = new AuthFilter(new HttpBaseProtocolFilter());

            _httpClient = new HttpClient(filter);

            _isConnectedToInternet = (null != NetworkInformation.GetInternetConnectionProfile());
            NetworkInformation.NetworkStatusChanged += OnNetworkStatusChanged;

            Logger.Initialize(LoggerTextBox, LoggerScrollViewer);
            await LogBackgroundEventsAsync();

            ShowStatus("Waiting for location...");

            try
            {
                _geolocator  = new Geolocator();
                _geoposition = await _geolocator.GetGeopositionAsync();

                ClearStatus();

                var position = _geoposition.Coordinate.Point.Position;
                Logger.Trace(TraceLevel.Info, String.Format("Current Location: {0}, Accuracy: {1} meters",
                                                            Logger.FormatLatLong(position.Latitude, position.Longitude),
                                                            _geoposition.Coordinate.Accuracy));

                // Initialize map
                var mapCenter = new Bing.Maps.Location(position.Latitude, position.Longitude);
                Map.SetView(mapCenter, Constants.DefaultMapZoomLevel);

                _currentLocationPushpin = new Bing.Maps.Pushpin();
                CurrentPositionMapLayer.Children.Add(_currentLocationPushpin);
                Bing.Maps.MapLayer.SetPosition(_currentLocationPushpin, mapCenter);

                // Register for position changed events
                _geolocator.PositionChanged += OnGeopositionChanged;

                // Loop through all background tasks to see if our background task is already registered
                foreach (var cur in BackgroundTaskRegistration.AllTasks)
                {
                    if (cur.Value.Name == _backgroundTaskName)
                    {
                        _geofenceTask = cur.Value;
                        break;
                    }
                }

                if (_geofenceTask != null)
                {
                    // Associate an event handler with the existing background task
                    _geofenceTask.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
                }
                else
                {
                    // Get permission for a background task from the user. If the user has already answered once,
                    // this does nothing and the user must manually update their preference via PC Settings.
                    var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

                    switch (backgroundAccessStatus)
                    {
                    case BackgroundAccessStatus.Unspecified:
                    case BackgroundAccessStatus.Denied:
                        ShowStatus("This application must be added to the lock screen in order to do automatic checkins.");
                        break;

                    default:
                        break;
                    }

                    // Register the background task.
                    var geofenceTaskBuilder = new BackgroundTaskBuilder();

                    geofenceTaskBuilder.Name           = _backgroundTaskName;
                    geofenceTaskBuilder.TaskEntryPoint = _backgroundTaskEntryPoint;

                    // Create a new location trigger
                    var trigger = new LocationTrigger(LocationTriggerType.Geofence);

                    // Associate the location trigger with the background task builder
                    geofenceTaskBuilder.SetTrigger(trigger);

                    // Ensure there is an internet connection before the background task is launched.
                    var condition = new SystemCondition(SystemConditionType.InternetAvailable);
                    geofenceTaskBuilder.AddCondition(condition);

                    // Register the background task
                    _geofenceTask = geofenceTaskBuilder.Register();

                    // Associate an event handler with the new background task
                    _geofenceTask.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);

                    Logger.Trace(TraceLevel.Debug, "Background registration succeeded");
                }
            }
            catch (System.UnauthorizedAccessException)
            {
                ShowStatus("Location access denied, please go to Settings -> Permissions to grant this app access to your location.");
                Logger.Trace(TraceLevel.Warn, "Access denied when getting location");
            }
            catch (TaskCanceledException)
            {
                ShowStatus("Location acquisition was canceled. Close and re-launch this app if you would like to try again.");
                Logger.Trace(TraceLevel.Warn, "Canceled getting location");
            }
            catch (Exception ex)
            {
                Logger.Trace(TraceLevel.Error, "Could not acquire location or register background trigger: " + Logger.FormatException(ex));
            }

            Settings.Changed += OnSettingsChanged;
            Logger.Trace(TraceLevel.Info, "Foursquare query limit setting: " + Settings.QueryLimit + " places");
            Logger.Trace(TraceLevel.Info, "Geofence creation radius setting: " + Settings.GeofenceRadiusMeters + " meters");
        }
Beispiel #21
0
        /// <summary>
        /// Used to make sure the background task is setup.
        /// </summary>
        public async Task EnsureBackgroundSetup()
        {
            // Try to find any task that we might have
            IBackgroundTaskRegistration foundTask = null;

            foreach (var task in BackgroundTaskRegistration.AllTasks)
            {
                if (task.Value.Name.Equals(c_backgroundTaskName))
                {
                    foundTask = task.Value;
                }
            }

            // For some dumb reason in WinRT we have to ask for permission to run in the background each time
            // our app is updated....
            String currentAppVersion = String.Format("{0}.{1}.{2}.{3}",
                                                     Package.Current.Id.Version.Build,
                                                     Package.Current.Id.Version.Major,
                                                     Package.Current.Id.Version.Minor,
                                                     Package.Current.Id.Version.Revision);

            if (String.IsNullOrWhiteSpace(AppVersionWithBackgroundAccess) || !AppVersionWithBackgroundAccess.Equals(currentAppVersion))
            {
                // Update current version
                AppVersionWithBackgroundAccess = currentAppVersion;

                // Remove access... stupid winrt.
                BackgroundExecutionManager.RemoveAccess();
            }

            // Request access to run in the background.
            BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync();

            LastSystemBackgroundUpdateStatus = (int)status;
            if (status != BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity && status != BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity)
            {
                m_baconMan.MessageMan.DebugDia("System denied us access from running in the background");
            }

            if (ImageUpdaterMan.IsLockScreenEnabled || ImageUpdaterMan.IsDeskopEnabled || MessageUpdaterMan.IsEnabled)
            {
                if (foundTask == null)
                {
                    // We need to make a new task
                    BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
                    builder.Name           = c_backgroundTaskName;
                    builder.TaskEntryPoint = "BaconBackground.BackgroundEntry";
                    builder.SetTrigger(new TimeTrigger(c_backgroundUpdateTime, false));
                    builder.SetTrigger(new MaintenanceTrigger(c_backgroundUpdateTime, false));

                    try
                    {
                        builder.Register();
                    }
                    catch (Exception e)
                    {
                        m_baconMan.TelemetryMan.ReportUnexpectedEvent(this, "failed to register background task", e);
                        m_baconMan.MessageMan.DebugDia("failed to register background task", e);
                    }
                }
            }
            else
            {
                if (foundTask != null)
                {
                    // We need to stop and unregister the background task.
                    foundTask.Unregister(true);
                }
            }
        }
Beispiel #22
0
        //</SnippetLaunchBackgroundTask>

        //<SnippetOnProgress>
        private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
        {
            string progress = "Progress: " + args.Progress + "%";

            Debug.WriteLine(progress);
        }
 private void AttachCompletedHandler(IBackgroundTaskRegistration task)
 {
     task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
 }
Beispiel #24
0
 /// <summary>
 /// Handle background task progress.
 /// </summary>
 /// <param name="task">The task that is reporting progress.</param>
 /// <param name="e">Arguments of the progress report.</param>
 private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
 {
     Progress[task.TaskId] = args.Progress;
 }
Beispiel #25
0
 /// <summary>
 /// Attach progress handler to a background task.
 /// </summary>
 /// <param name="task">The task to attach progress handler to.</param>
 private void AttachProgressHandler(IBackgroundTaskRegistration task)
 {
     task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
 }
Beispiel #26
0
 private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
 {
     Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                         () => ViewModel.LoadDataAsync());
 }
Beispiel #27
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (taskAdvertisementWatcher != null)
            {
                taskAdvertisementWatcher.Completed -= OnBackgroundTaskCompleted;
                taskAdvertisementWatcher.Unregister(true);
                taskAdvertisementWatcher      = null;
                btnRegisterUnregister.Content = "Register Background Task";
            }
            else
            {
                //Register the new task
                // Applications registering for background trigger must request for permission.
                BackgroundExecutionManager.RequestAccessAsync().AsTask().ContinueWith(async(r) =>
                {
                    if (r.IsFaulted || r.IsCanceled)
                    {
                        return;
                    }
                    if ((r.Result == BackgroundAccessStatus.Denied) || (r.Result == BackgroundAccessStatus.Unspecified))
                    {
                        await new MessageDialog("Not able to run in background. Application must given permission to be added to lock screen.").ShowAsync();
                        Application.Current.Exit();
                    }

                    // Create and initialize a new trigger to configure it.
                    trigger = new BluetoothLEAdvertisementWatcherTrigger();
                    // Add the manufacturer data to the advertisement filter on the trigger:
                    trigger.AdvertisementFilter.Advertisement.iBeaconSetAdvertisement(new iBeaconData());
                    // By default, the sampling interval is set to be disabled, or the maximum sampling interval supported.
                    // The sampling interval set to MaxSamplingInterval indicates that the event will only trigger once after it comes into range.
                    // Here, set the sampling period to 1 second, which is the minimum supported for background.
                    trigger.SignalStrengthFilter.SamplingInterval = TimeSpan.FromMilliseconds(1000);

                    // At this point we assume we haven't found any existing tasks matching the one we want to register
                    // First, configure the task entry point, trigger and name
                    var builder            = new BackgroundTaskBuilder();
                    builder.TaskEntryPoint = taskEntryPoint;
                    builder.SetTrigger(trigger);
                    builder.Name = taskName;

                    // Now perform the registration. The registration can throw an exception if the current
                    // hardware does not support background advertisement offloading
                    try
                    {
                        taskAdvertisementWatcher = builder.Register();
                        Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
                        {
                            // For this scenario, attach an event handler to display the result processed from the background task
                            taskAdvertisementWatcher.Completed += OnBackgroundTaskCompleted;
                            btnRegisterUnregister.Content       = "Unregister Background Task";
                        });
                    }
                    catch (Exception ex)
                    {
                        taskAdvertisementWatcher = null;
                        switch ((uint)ex.HResult)
                        {
                        case (0x80070032):     // ERROR_NOT_SUPPORTED
                            Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
                            {
                                await new MessageDialog("The hardware does not support background advertisement offload.").ShowAsync();
                                Application.Current.Exit();
                            });
                            break;

                        default:
                            throw ex;
                        }
                    }
                });
            }
        }
Beispiel #28
0
        private async void Register()
        {
            try
            {
                // Get permission for a background task from the user. If the user has already answered once,
                // this does nothing and the user must manually update their preference via PC Settings.
                BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

                switch (backgroundAccessStatus)
                {
                case BackgroundAccessStatus.Unspecified:
                case BackgroundAccessStatus.Denied:
                    Debug.WriteLine("Not able to run in background. Application must be added to the lock screen.");
                    this.IsTaskRegistered = false;
                    break;

                default:
                    // BckgroundTask is allowed
                    Debug.WriteLine("Geofence background task registered.");

                    // Need to request access to location
                    // This must be done with the background task registration
                    // because the background task cannot display UI.
                    bool locationAccess = await RequestLocationAccess();

                    if (locationAccess)
                    {
                        BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder();

                        geofenceTaskBuilder.Name           = nameof(GeofenceBackgroundTask);
                        geofenceTaskBuilder.TaskEntryPoint = typeof(GeofenceBackgroundTask).ToString();

                        // Create a new location trigger
                        var trigger = new LocationTrigger(LocationTriggerType.Geofence);

                        // Associate the locationi trigger with the background task builder
                        geofenceTaskBuilder.SetTrigger(trigger);
                        geofenceTaskBuilder.AddCondition(new SystemCondition(SystemConditionType.BackgroundWorkCostNotHigh));

                        // Register the background task
                        _geofenceTask = geofenceTaskBuilder.Register();

                        this.IsTaskRegistered = true;
                    }

                    break;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            if (this.IsTaskRegistered)
            {
                var successDialog = new MessageDialog("Task registered");
                await successDialog.ShowAsync();
            }
            else
            {
                var errorDialog = new MessageDialog("Error registering task");
                await errorDialog.ShowAsync();
            }
        }
 /// <summary>
 /// Attach progress and completed handers to a background task.
 /// </summary>
 /// <param name="task">The task to attach progress and completed handlers to.</param>
 private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task)
 {
     task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
     task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
 }
 /// <summary>
 /// Unregisters a background task.
 /// </summary>
 /// <param name="backgroundTask">A background task that was previously registered with the system</param>
 /// <param name="forceExit">Force the background task to quit if it is currently running (at the time of unregistering). Default value is true.</param>
 public static void Unregister(IBackgroundTaskRegistration backgroundTask, bool forceExit = true)
 {
     backgroundTask?.Unregister(forceExit);
 }
Beispiel #31
0
 public OrderModule(IRegionManager regionManager, IBackgroundTaskRegistration taskRegistration)
 {
     _regionManager    = regionManager;
     _taskRegistration = taskRegistration;
 }
 public static IAsyncAction TryUpdateAsyncWithAsyncAction(IBackgroundTaskRegistration taskRegistration)
 {
     return(TryUpdateAsync(taskRegistration).AsAsyncAction());
 }
Beispiel #33
0
        //</SnippetOnProgress>

        //<SnippetOnCompleted>
        private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
        {
            Debug.WriteLine(" background task complete");
        }
 /// <summary>
 /// Handle background task completion.
 /// </summary>
 /// <param name="task">The task that is reporting completion.</param>
 /// <param name="e">Arguments of the completion report.</param>
 private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
 {
     UpdateUI();
 }
 void GetTask()
 {
     this.taskRegistration            = BackgroundTaskRegistration.AllTasks.Values.First();
     this.taskRegistration.Completed += OnCompleted;
     this.taskRegistration.Progress  += OnProgress;
 }
 /// <summary>
 /// Handle background task progress.
 /// </summary>
 /// <param name="task">The task that is reporting progress.</param>
 /// <param name="e">Arguments of the progress report.</param>
 private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
 {
     var progress = "Progress: " + args.Progress + "%";
     BackgroundTaskSample.ServicingCompleteTaskProgress = progress;
     UpdateUI();
 }
        /// <summary>
        /// Handle background task progress.
        /// </summary>
        /// <param name="task">The task that is reporting progress.</param>
        /// <param name="e">Arguments of the progress report.</param>
        //private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
        //{
        //    var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        //    {
        //        var progress = "Progress: " + args.Progress + "%";
        //        BackgroundTaskSample.ServicingCompleteTaskProgress = progress;
        //        UpdateUI();
        //    });
        //}

        /// <summary>
        /// Handle background task completion.
        /// </summary>
        /// <param name="task">The task that is reporting completion.</param>
        /// <param name="e">Arguments of the completion report.</param>
        private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
        {
            //UpdateUI();
            Helpers.ShowToast("dksingh");
        }
Beispiel #38
0
 private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task)
 {
     // 为任务增加 Progress 和 Completed 事件监听,以便前台 app 接收后台任务的进度汇报和完成汇报
     task.Progress  += new BackgroundTaskProgressEventHandler(OnProgress);
     task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
 }
 private void SubscribeBackgroundTaskEvents(IBackgroundTaskRegistration registration)
 {
     registration.Completed += OnRegisteredTaskCompleted;
     registration.Progress  += OnRegisteredTaskProgress;
 }
 private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
 {
     var settings = Windows.Storage.ApplicationData.Current.LocalSettings;
     var key      = task.TaskId.ToString();
     var message  = settings.Values[key].ToString();
 }
 /// <summary>
 /// Attach progress and completed handers to a background task.
 /// </summary>
 /// <param name="task">The task to attach progress and completed handlers to.</param>
 private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task)
 {
     task.Progress  += new BackgroundTaskProgressEventHandler(OnProgress);
     task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
 }
 /// <summary>
 /// Invoked when application execution is being resumed.
 /// </summary>
 /// <param name="sender">The source of the resume request.</param>
 /// <param name="e"></param>
 private void App_Resuming(object sender, object e)
 {
     // Get the existing task if already registered
     if (taskRegistration == null)
     {
         // Find the task if we previously registered it
         foreach (var task in BackgroundTaskRegistration.AllTasks.Values)
         {
             if (task.Name == taskName)
             {
                 taskRegistration = task;
                 taskRegistration.Completed += OnBackgroundTaskCompleted;
                 break;
             }
         }
     }
     else
     {
         taskRegistration.Completed += OnBackgroundTaskCompleted;
     }
 }
 /// <summary>
 /// Register completion handler for registered background task on application startup.
 /// </summary>
 /// <param name="task">The task to attach progress and completed handlers to.</param>
 private bool RegisterCompletedHandlerforBackgroundTask(IBackgroundTaskRegistration task)
 {
     bool taskRegistered = false;
     try
     {
         //Associate background task completed event handler with background task.
         task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
         taskRegistered = true;
     }
     catch (Exception ex)
     {
         rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
     }
     return taskRegistered;
 }
 /// <summary>
 /// Invoked as an event handler when the Stop button is pressed.
 /// </summary>
 /// <param name="sender">Instance that triggered the event.</param>
 /// <param name="e">Event data describing the conditions that led to the event.</param>
 private void StopButton_Click(object sender, RoutedEventArgs e)
 {
     // Unregistering the background task will stop scanning if this is the only client requesting scan
     // First get the existing tasks to see if we already registered for it
     if (taskRegistration != null)
     {
         taskRegistration.Unregister(true);
         taskRegistration = null;
         rootPage.NotifyUser("Background watcher unregistered.", NotifyType.StatusMessage);
     }
     else
     {
         // At this point we assume we haven't found any existing tasks matching the one we want to unregister
         rootPage.NotifyUser("No registered background watcher found.", NotifyType.StatusMessage);
     }
 }
        private void RegisterBackgroundTask(DeviceWatcherTrigger deviceWatcherTrigger)
        {
            BackgroundTaskBuilder taskBuilder;

            // First see if we already have this background task registered. If so, unregister
            // it before we register it with the new trigger.

            foreach (var task in BackgroundTaskRegistration.AllTasks)
            {
                if (backgroundTaskName == task.Value.Name)
                {
                    UnregisterBackgroundTask(task.Value);
                }
            }

            taskBuilder = new BackgroundTaskBuilder();
            taskBuilder.Name = backgroundTaskName;
            taskBuilder.TaskEntryPoint = "BackgroundDeviceWatcherTaskCs.BackgroundDeviceWatcher";
            taskBuilder.SetTrigger(deviceWatcherTrigger);

            backgroundTaskRegistration = taskBuilder.Register();
            backgroundTaskRegistration.Completed += new BackgroundTaskCompletedEventHandler(OnTaskCompleted);
        }
Beispiel #46
0
        async private void RegisterGeoFence()
        {
            try
            {
                BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();
                
                BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder();

                geofenceTaskBuilder.Name = SampleBackgroundTaskName;
                geofenceTaskBuilder.TaskEntryPoint = SampleBackgroundTaskEntryPoint;
                var trigger = new LocationTrigger(LocationTriggerType.Geofence);
                
                geofenceTaskBuilder.SetTrigger(trigger);
                _geofenceTask = geofenceTaskBuilder.Register();
                
            }
            catch
            {
            }
        }
Beispiel #47
0
        /// <summary>
        /// When the user presses the run button, start the background watcher or alert the user that one is already registered
        /// </summary>
        /// <param name="sender">Instance that triggered the event.</param>
        /// <param name="e">Event data describing the conditions that led to the event.</param>
        private async void RunButton_Click(object sender, RoutedEventArgs e)
        {
            // Registering a background trigger if it is not already registered. It will start background scanning.
            // First get the existing tasks to see if we already registered for it
            if (taskRegistration != null)
            {
                rootPage.NotifyUser("Background watcher already registered.", NotifyType.StatusMessage);
                return;
            }
            else
            {
                rootPage.NotifyUser("Registering background watcher.", NotifyType.StatusMessage);

                // Applications registering for background trigger must request for permission.
                BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

                // Here, we do not fail the registration even if the access is not granted. Instead, we allow
                // the trigger to be registered and when the access is granted for the Application at a later time,
                // the trigger will automatically start working again.

                // At this point we assume we haven't found any existing tasks matching the one we want to register
                // First, configure the task entry point, trigger and name
                var builder = new BackgroundTaskBuilder();
                builder.TaskEntryPoint = taskEntryPoint;
                builder.SetTrigger(trigger);
                builder.Name = taskName;

                // Now perform the registration. The registration can throw an exception if the current
                // hardware does not support background advertisement offloading
                try
                {
                    taskRegistration = builder.Register();

                    // For this scenario, attach an event handler to display the result processed from the background task
                    taskRegistration.Completed += OnBackgroundTaskCompleted;

                    // Even though the trigger is registered successfully, it might be blocked. Notify the user if that is the case.
                    if ((backgroundAccessStatus == BackgroundAccessStatus.Denied) || (backgroundAccessStatus == BackgroundAccessStatus.Unspecified))
                    {
                        rootPage.NotifyUser("Not able to run in background. Application must given permission to be added to lock screen.",
                                            NotifyType.ErrorMessage);
                    }
                    else
                    {
                        rootPage.NotifyUser("Background watcher registered.", NotifyType.StatusMessage);
                    }
                }
                catch (Exception ex)
                {
                    switch ((uint)ex.HResult)
                    {
                    case (0x80070032):     // ERROR_NOT_SUPPORTED
                        rootPage.NotifyUser("The hardware does not support background advertisement offload.", NotifyType.ErrorMessage);
                        break;

                    default:
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                        throw ex;
                    }
                }
            }
        }
 private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
 {
 }
 /// <summary>
 /// Handle background task completion.
 /// </summary>
 /// <param name="task">The task that is reporting completion.</param>
 /// <param name="e">Arguments of the completion report.</param>
 private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
 {
     UpdateUI();
 }
Beispiel #50
0
        public bool TryRegisterBackgroundTaskOnce(string name, string entryPoint, IBackgroundTrigger trigger, out IBackgroundTaskRegistration registeredTask)
        {
            foreach (var task in BackgroundTaskRegistration.AllTasks)
            {
                if (task.Value.Name == name)
                {
                    registeredTask = task.Value;
                    return(true);
                }
            }
            var taskBuilder = new BackgroundTaskBuilder
            {
                Name           = name,
                TaskEntryPoint = entryPoint
            };

            taskBuilder.SetTrigger(trigger);
            try
            {
                registeredTask = taskBuilder.Register();
            }
            catch (Exception e)
            {
                DebugLogger.LogException(e);
                registeredTask = null;
                return(false);
            }

            return(true);
        }
 /// <summary>
 /// Handle background task progress.
 /// </summary>
 /// <param name="task">The task that is reporting progress.</param>
 /// <param name="e">Arguments of the progress report.</param>
 private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
 {
     var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         var progress = "Progress: " + args.Progress + "%";
         BackgroundTaskSample.ServicingCompleteTaskProgress = progress;
         UpdateUI();
     });
 }
 public static void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
 {
 }
        /// <summary>
        /// Invoked as an event handler when the Run button is pressed.
        /// </summary>
        /// <param name="sender">Instance that triggered the event.</param>
        /// <param name="e">Event data describing the conditions that led to the event.</param>
        private async void RunButton_Click(object sender, RoutedEventArgs e)
        {
            // Registering a background trigger if it is not already registered. It will start background scanning.
            // First get the existing tasks to see if we already registered for it
            if (taskRegistration != null)
            {
                rootPage.NotifyUser("Background watcher already registered.", NotifyType.StatusMessage);
                return;
            }
            else
            {
                // Applications registering for background trigger must request for permission.
                BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();
                // Here, we do not fail the registration even if the access is not granted. Instead, we allow 
                // the trigger to be registered and when the access is granted for the Application at a later time,
                // the trigger will automatically start working again.

                // At this point we assume we haven't found any existing tasks matching the one we want to register
                // First, configure the task entry point, trigger and name
                var builder = new BackgroundTaskBuilder();
                builder.TaskEntryPoint = taskEntryPoint;
                builder.SetTrigger(trigger);
                builder.Name = taskName;

                // Now perform the registration. The registration can throw an exception if the current 
                // hardware does not support background advertisement offloading
                try
                {
                    taskRegistration = builder.Register();

                    // For this scenario, attach an event handler to display the result processed from the background task
                    taskRegistration.Completed += OnBackgroundTaskCompleted;

                    // Even though the trigger is registered successfully, it might be blocked. Notify the user if that is the case.
                    if ((backgroundAccessStatus == BackgroundAccessStatus.Denied) || (backgroundAccessStatus == BackgroundAccessStatus.Unspecified))
                    {
                        rootPage.NotifyUser("Not able to run in background. Application must given permission to be added to lock screen.",
                            NotifyType.ErrorMessage);
                    }
                    else
                    {
                        rootPage.NotifyUser("Background watcher registered.", NotifyType.StatusMessage);
                    }
                }
                catch (Exception ex)
                {
                    switch ((uint)ex.HResult)
                    {
                        case (0x80070032): // ERROR_NOT_SUPPORTED
                            rootPage.NotifyUser("The hardware does not support background advertisement offload.", NotifyType.ErrorMessage);
                            break;
                        default:
                            throw ex;
                    }
                }
            }
        }
 /// <summary>
 /// Note: This handler is called only if the task completed while the application was in the foreground.
 /// </summary>
 private void OnTimedBackgroundTaskCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
 {
     Logger.Debug("BackgroundTaskManager.OnTimedBackgroundTaskCompleted()");
 }
Beispiel #55
0
 private void UnregisterGeoFence()
 {
     if (null != _geofenceTask)
     {
         _geofenceTask.Unregister(true);
         _geofenceTask = null;
     }
 }
 /// <summary>
 /// Note: This handler is called only if the task completed while the application was in the foreground.
 /// </summary>
 private void OnAdvertisementWatcherBackgroundTaskCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
 {
     Logger.Debug("BackgroundTaskManager.OnAdvertisementWatcherBackgroundTaskCompleted()");
 }
Beispiel #57
0
 /// <summary>
 /// Event fires after background task completes.
 /// </summary>
 /// <param name="task"></param>
 /// <param name="args"></param>
 private void OnCortanaMakeTaskCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
 {
    Windows.Storage.ApplicationDataContainer settings = Windows.Storage.ApplicationData.Current.LocalSettings;
    string key = task.TaskId.ToString();
    string message = settings.Values[key].ToString();
 }
        /// <summary>
        /// This is the click handler for the 'Register' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void RegisterBackgroundTask(object sender, RoutedEventArgs e)
        {
            try
            {
                // Get permission for a background task from the user. If the user has already answered once,
                // this does nothing and the user must manually update their preference via PC Settings.
                BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

                // Regardless of the answer, register the background task. If the user later adds this application
                // to the lock screen, the background task will be ready to run.
                // Create a new background task builder
                BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder();

                geofenceTaskBuilder.Name           = SampleBackgroundTaskName;
                geofenceTaskBuilder.TaskEntryPoint = SampleBackgroundTaskEntryPoint;

                // Create a new location trigger
                var trigger = new LocationTrigger(LocationTriggerType.Geofence);

                // Associate the locationi trigger with the background task builder
                geofenceTaskBuilder.SetTrigger(trigger);

                // If it is important that there is user presence and/or
                // internet connection when OnCompleted is called
                // the following could be called before calling Register()
                // SystemCondition condition = new SystemCondition(SystemConditionType.UserPresent | SystemConditionType.InternetAvailable);
                // geofenceTaskBuilder.AddCondition(condition);

                // Register the background task
                geofenceTask = geofenceTaskBuilder.Register();

                // Associate an event handler with the new background task
                geofenceTask.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);

                UpdateButtonStates(/*registered:*/ true);

                switch (backgroundAccessStatus)
                {
                case BackgroundAccessStatus.Unspecified:
                case BackgroundAccessStatus.Denied:
                    rootPage.NotifyUser("This application must be added to the lock screen before the background task will run.", NotifyType.ErrorMessage);
                    break;

                default:
                    // Ensure we have presented the location consent prompt (by asynchronously getting the current
                    // position). This must be done here because the background task cannot display UI.
                    GetGeopositionAsync();
                    break;
                }
            }
            catch (Exception ex)
            {
                // HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED) == 0x80070032
                const int RequestNotSupportedHResult = unchecked ((int)0x80070032);

                if (ex.HResult == RequestNotSupportedHResult)
                {
                    rootPage.NotifyUser("Location Simulator not supported.  Could not get permission to add application to the lock screen, this application must be added to the lock screen before the background task will run.", NotifyType.StatusMessage);
                }
                else
                {
                    rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
                }

                UpdateButtonStates(/*registered:*/ false);
            }
        }