Exemplo n.º 1
0
        public async Task InitializeBackgroundGeolocation()
        {
            // Loop through all background tasks to see if SampleGeofenceBackgroundTask is already registered
            foreach (var task in BackgroundTaskRegistration.AllTasks)
            {
                if (task.Value.Name == Constants.ApplicationTriggerBackgroundTaskName)
                {
                    _applicationTriggerBackgroundTask = task.Value;
                }
            }

            if (_applicationTriggerBackgroundTask == null)
            {
                // Create a new trigger
                //applicationtrigger = new ApplicationTrigger();

                SystemCondition condition = new SystemCondition(SystemConditionType.UserNotPresent | SystemConditionType.InternetAvailable);

                _applicationTriggerBackgroundTask = await BackgroundTaskHelper.RegisterBackgroundTask(
                    Constants.ApplicationTriggerBackgroundTaskEntryPoint,
                    Constants.ApplicationTriggerBackgroundTaskName,
                    applicationtrigger,
                    null);

                var result = await applicationtrigger.RequestAsync();

                if (result.Equals(ApplicationTriggerResult.Allowed))
                {
                    Toast.ShowToast("Location Monitoring Started");
                }
            }

            await LoadExitingLocations();
        }
Exemplo n.º 2
0
        /// <summary>
        ///     Invoked when the application is launched normally by the end user.  Other entry points
        ///     will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
            CoreApp.CurrentPlatform = AppPlatform.UWP;
            base.OnLaunched(e);
#if !DEBUG
            AppCenter.Start("1fba816a-eea6-42a8-bf46-0c0fcc1589db", typeof(Analytics), typeof(Crashes));
#endif
            if (e.PreviousExecutionState != ApplicationExecutionState.Running)
            {
                ApplicationLanguages.PrimaryLanguageOverride = GlobalizationPreferences.Languages[0];

                Xamarin.Forms.Forms.Init(e);
                new MoneyFox.App();

                BackgroundTaskHelper.Register(typeof(ClearPaymentsTask), new TimeTrigger(60, false));
                BackgroundTaskHelper.Register(typeof(RecurringPaymentTask), new TimeTrigger(60, false));

                mainView.ViewModel = Mvx.IoCProvider.Resolve <MainViewModel>();
                (mainView.ViewModel as MainViewModel)?.ShowAccountListCommand.ExecuteAsync();

                OverrideTitleBarColor();

                //If Jump Lists are supported, add them
                if (ApiInformation.IsTypePresent("Windows.UI.StartScreen.JumpList"))
                {
                    await SetJumplist();
                }

                await CallRateReminder();
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Arrival event as a NetworkMonitorEventListener
        /// </summary>
        /// <param name="nme"> NetworkMonitorEvent add </param>
        public virtual void deviceArrival(DeviceMonitorEvent dme)
        {
            for (int i = 0; i < dme.DeviceCount; i++)
            {
                Debug.WriteLine("ADD: " + dme.getPathForContainerAt(i) + dme.getAddressAsStringAt(i));

                // if new devices is a TemperatureContainter the start a thread to read it
                OneWireContainer owc = dme.getContainerAt(i);

                if (owc is TemperatureContainer)
                {
//TODO                    SetValue("TemperatureContainer", owc);
//TODO                    SetValue("OWPath", dme.getPathForContainerAt(i));

                    var t = Task <BackgroundTaskRegistration> .Run(() =>
                    {
                        return(BackgroundTaskHelper.Register(
                                   WatchTempBackgroundTaskEntryPoint,
                                   WatchTempBackgroundTaskName,
                                   new SystemTrigger(SystemTriggerType.TimeZoneChange, false),
                                   null));
                    });

                    t.Wait();

                    // add to vector for later cleanup
                    watchers.Add(t.Result);
                }
            }
        }
Exemplo n.º 4
0
        private async Task InitializeWeather(Reservation currentTrip)
        {
            WeatherForecast weather = null;

            if (currentTrip != null)
            {
                var flightInfo = currentTrip.DepartureFlight.FlightInfo;
                var locationId = flightInfo.Flight.Destination.LocationId;
                var departure  = flightInfo.Departure ?? DateTime.Now;

                weather = await _data.GetWeatherForecastByIdAsync(locationId, departure);

                ApplicationData.Current.LocalSettings.Values["locationId"]   = locationId;
                ApplicationData.Current.LocalSettings.Values["locationName"] = flightInfo.Flight.Source.City;
                ApplicationData.Current.LocalSettings.Values["departure"]    = string.Format("{0:yyyy-MM-dd}", departure);
            }

            Weather = weather;

            var weatherUpdateTask = BackgroundTaskHelper.FindRegisteredTask(Constants.WeatherTaskName);

            if (weatherUpdateTask != null)
            {
                weatherUpdateTask.Completed += WeatherUpdateTaskOnCompleted;
            }
        }
Exemplo n.º 5
0
        private async void Initialize()
        {
            BackgroundTaskHelper.RegisterBackgroundTaskAsync();

            Resolver.Resolve <ILiveTileUpdater>().UpdateLiveTile();

            // initialize azure mobile service offline cache
            await Resolver.Resolve <IDrinkLogRepository>().InitLocalStoreAsync();

            // write old entries to db otherwise the settings property will get too large
            var synctask = Resolver.Resolve <IDrinkLogRepository>().SyncCacheEntriesAsync();

            // calculate last weeks max and average
            var task  = Resolver.Resolve <IDrinkLogRepository>().GetLastWeeksAverageAndMax();
            var task2 = Resolver.Resolve <IDrinkLogRepository>().GetThisWeeksAverageAndMax();

            // new installation -> runs first setup
            Type firstPage = null;

            if (Resolver.Resolve <ISettingsStore>().FirstStart)
            {
                firstPage = typeof(SetupUnitSystemPage);
            }
            else
            {
                firstPage = typeof(RootPage);
            }



            Frame.Navigate(firstPage, "ClearBackStack");
        }
Exemplo n.º 6
0
        private void RegisterBackgroundTask()
        {
            var task = BackgroundTaskHelper.Register(typeof(BiliBili.Background.BackgroundTask), new TimeTrigger(15, true), true, true, null);

            task.Progress  += TaskOnProgress;
            task.Completed += TaskOnCompleted;
        }
Exemplo n.º 7
0
        /// <summary>
        ///     Invoked when the application is launched normally by the end user.  Other entry points
        ///     will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
#if !DEBUG
            MobileCenter.Start("1fba816a-eea6-42a8-bf46-0c0fcc1589db", typeof(Analytics), typeof(Crashes));
#endif
            if (e.PreviousExecutionState != ApplicationExecutionState.Running)
            {
                var mainView = new MainView {
                    Language = ApplicationLanguages.Languages[0]
                };

                Window.Current.Content = mainView;
                ApplicationLanguages.PrimaryLanguageOverride = GlobalizationPreferences.Languages[0];

                Xamarin.Forms.Forms.Init(e);

                // When the navigation stack isn't restored, navigate to the first page
                // suppressing the initial entrance animation.
                var setup = new Setup(mainView.MainFrame);
                setup.Initialize();

                var start = Mvx.Resolve <IMvxAppStart>();
                start.Start();

                BackgroundTaskHelper.Register(typeof(ClearPaymentsTask), new TimeTrigger(60, false));
                BackgroundTaskHelper.Register(typeof(RecurringPaymentTask), new TimeTrigger(60, false));
                Mvx.Resolve <IBackgroundTaskManager>().StartBackupSyncTask(60);

                mainView.ViewModel = Mvx.Resolve <MenuViewModel>();

                OverrideTitleBarColor();

                //If Jump Lists are supported, add them
                if (ApiInformation.IsTypePresent("Windows.UI.StartScreen.JumpList"))
                {
                    await SetJumplist();
                }

                await CallRateReminder();
            }

            //OverrideTitleBarColor();

            //When jumplist is selected navigate to appropriate tile
            var tileHelper = Mvx.Resolve <TileHelper>();
            if (e.Arguments == Constants.ADD_INCOME_TILE_ID)
            {
                await tileHelper.DoNavigation(Constants.ADD_INCOME_TILE_ID);
            }
            else if (e.Arguments == Constants.ADD_EXPENSE_TILE_ID)
            {
                await tileHelper.DoNavigation(Constants.ADD_EXPENSE_TILE_ID);
            }
            else if (e.Arguments == Constants.ADD_TRANSFER_TILE_ID)
            {
                await tileHelper.DoNavigation(Constants.ADD_TRANSFER_TILE_ID);
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }
Exemplo n.º 8
0
 public void TestCleanUp()
 {
     if (BackgroundTaskHelper.IsBackgroundTaskRegistered("TaskName"))
     {
         BackgroundTaskHelper.Unregister("TaskName");
     }
 }
Exemplo n.º 9
0
 private void UnRegisterBackgroundTask()
 {
     BackgroundTaskHelper.UnRegisterBackgroundTask(
         typeof(Sodu.CheckUpdateTask.BookShelfCheckTask),
         "BookShelfCheckTask",
         new TimeTrigger(15, false),
         null);
 }
Exemplo n.º 10
0
 private void UnRegisterTasks()
 {
     BackgroundTaskHelper.Unregister("SampleBackgroundTask");
     BackgroundTaskHelper.Unregister("ToastBackgroundTask");
     BackgroundTaskHelper.Unregister(TASK_NAME);
     register.Content = "Remember Me";
     Registered       = false;
 }
Exemplo n.º 11
0
 private async void RegisterBGTask(bool isUpdated)
 {
     if (isUpdated)
     {
         await BackgroundTaskHelper.OnAppUpdate();
     }
     await BackgroundTaskHelper.RegisterBackgroundTasksAsync();
 }
Exemplo n.º 12
0
        public async void Create(string backgroundTaskName, string backgroundTaskEntryPoint, int time, IBackgroundCondition backgroundCondition)
        {
            IBackgroundTrigger backgroundTrigger = new TimeTrigger((uint)time, false);
            var   task = BackgroundTaskHelper.RegisterBackgroundTask(backgroundTaskEntryPoint, backgroundTaskName, backgroundTrigger, backgroundCondition);
            await task;

            AttachProgressAndCompletedHandlers(task.Result);
        }
Exemplo n.º 13
0
        private static void HandleBackgroundSnoozeActivation(ToastNotificationActionTriggerDetail details)
        {
            string snoozeMinutesTxt = (string)details.UserInput[INPUT_SNOOZEMINUTES];
            uint   snoozeMinutes    = uint.Parse(snoozeMinutesTxt);

            // Register a time trigger background task to fire at the requested snooze time, which will then pop a new notification
            BackgroundTaskHelper.Register(TOAST_TIME_TRIGGER_BACKGROUND_TASK, new TimeTrigger(snoozeMinutes, oneShot: true));
        }
Exemplo n.º 14
0
 private async Task RegisterBackgroundTask()
 {
     var task = await BackgroundTaskHelper.RegisterBackgroundTask(
         typeof(Sodu.CheckUpdateTask.BookShelfCheckTask),
         "BookShelfCheckTask",
         new TimeTrigger(120, false),
         null);
 }
Exemplo n.º 15
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var task = BackgroundTaskHelper.RegisterBackgroundTask(taskEntryPoint: "Tasks.OutOfProcessBgTask",
                                                                   taskName: "OutOfProcessBgTask",
                                                                   trigger: new MaintenanceTrigger(freshnessTime: 15, oneShot: false),
                                                                   condition: new SystemCondition(SystemConditionType.InternetAvailable));

            AttachProgressAndCompletedHandlers(task);
        }
Exemplo n.º 16
0
        /// <summary>
        /// 注销后台任务
        /// </summary>
        /// <param name="type">类型</param>
        public void UnRegisterBackgroundTask(string type)
        {
            string backgroundTaskName = $"{type}NotificationTask";

            if (BackgroundTaskHelper.IsBackgroundTaskRegistered(backgroundTaskName))
            {
                BackgroundTaskHelper.Unregister(backgroundTaskName);
            }
        }
Exemplo n.º 17
0
        public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
        {
            // register background tasks
            // background task to update next lesson in tile
            BackgroundTaskHelper.RegisterBackgroundTask("TimetableBackgroundTask", "BackgroundTasks.TimetableBackgroundTask", 15);

            NavigationService.Navigate(typeof(Views.TimetablePage));
            await Task.CompletedTask;
        }
Exemplo n.º 18
0
        /// <inheritdoc />
        public void StartBackupSyncTask()
        {
            BackgroundTaskRegistration registered =
                BackgroundTaskHelper.Register(typeof(SyncBackupTask),
                                              new TimeTrigger((uint)(settingsManager.BackupSyncRecurrence * 60),
                                                              true));

            registered.Completed += RegisteredOnCompleted;
        }
Exemplo n.º 19
0
        private void UninitializeWeather()
        {
            var weatherUpdateTask = BackgroundTaskHelper.FindRegisteredTask(Constants.WeatherTaskName);

            if (weatherUpdateTask != null)
            {
                weatherUpdateTask.Completed -= WeatherUpdateTaskOnCompleted;
            }
        }
Exemplo n.º 20
0
        private async void appTriggerTask_Click(object sender, RoutedEventArgs e)
        {
            bool result = await BackgroundTaskHelper.RegisterApplicationTriggerBackgroundTask(
                LocalizableStrings.BACKGROUND_TASK_APPTRIGGER_NAME, LocalizableStrings.BACKGROUND_TASK_APPTRIGGER_ENTRYPOINT);

            if (result)
            {
                status.Log(LocalizableStrings.BACKGROUND_TASK_REGISTRATION_SUCCESS);
            }
        }
        // NOTE: Both the ToastsPage and the BackgroundTaskPage can register/unregister the same background task.

        private async void registerTask_Click(object sender, RoutedEventArgs e)
        {
            bool result = await BackgroundTaskHelper.RegisterTimeZoneChangeBackgroundTask(
                LocalizableStrings.BACKGROUND_TASK_TIMEZONE_NAME, LocalizableStrings.BACKGROUND_TASK_TIMEZONE_ENTRYPOINT);

            if (result)
            {
                status.Log(LocalizableStrings.BACKGROUND_TASK_REGISTRATION_SUCCESS);
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Depart event as a NetworkMonitorEventListener
        /// </summary>
        /// <param name="nme"> NetworkMonitorEvent depart </param>
        public virtual void deviceDeparture(DeviceMonitorEvent dme)
        {
            for (int i = 0; i < dme.DeviceCount; i++)
            {
                Debug.WriteLine("REMOVE: " + dme.getPathForContainerAt(i) + dme.getAddressAsStringAt(i));

                // kill the temp watcher
                BackgroundTaskHelper.Unregister(WatchTempBackgroundTaskName);
            }
        }
Exemplo n.º 23
0
        private bool IsBackgroundTaskRegistered(string taskName)
        {
            if (BackgroundTaskHelper.IsBackgroundTaskRegistered(taskName))
            {
                // Background task already registered.
                StatusMessage.Text = "Background Task already registered";
                return(true);
            }

            return(false);
        }
Exemplo n.º 24
0
        public void Test_BackgroundTaskHelper_GetBackgroundTask_WithValidTask()
        {
            BackgroundTaskRegistration registeredTask = BackgroundTaskHelper.Register("TaskName", new TimeTrigger(15, true));

            if (registeredTask == null)
            {
                Assert.Inconclusive("Task failed to register");
            }

            Assert.IsNotNull(BackgroundTaskHelper.GetBackgroundTask("TaskName"));
        }
Exemplo n.º 25
0
 public void RegisterLogin(bool reg)
 {
     if (reg)
     {
         BackgroundTaskHelper.Register(typeof(LoginTask), new SystemTrigger(SystemTriggerType.NetworkStateChange, false), true, true);
     }
     else
     {
         BackgroundTaskHelper.Unregister(typeof(LoginTask));
     }
 }
Exemplo n.º 26
0
        /// <summary>
        /// Registers a particular bg tasks specified by <paramref name="backgroundTask"/>
        /// </summary>
        /// <param name="backgroundTask">The background task to register</param>
        /// <param name="restart">Indicates if the registration of the bg task is mandatory(True by default)</param>
        public static void RegisterBackgroundTask(BackgroundTaskType backgroundTask, int bgTaskInterval = 0, bool restart = true)
        {
            string             bgTaskName;
            Type               bgTaskType;
            IBackgroundTrigger trigger;
            var conditions = new List <IBackgroundCondition>();

            switch (backgroundTask)
            {
            case BackgroundTaskType.ANY:
                throw new ArgumentException("Is not allowed to register all bg tasks at the same time");

            case BackgroundTaskType.SYNC:
                bgTaskName = nameof(SyncBackgroundTask);
                bgTaskType = typeof(SyncBackgroundTask);
                trigger    = new TimeTrigger((uint)bgTaskInterval, false);
                conditions.Add(new SystemCondition(SystemConditionType.FreeNetworkAvailable));
                conditions.Add(new SystemCondition(SystemConditionType.InternetAvailable));
                break;

            case BackgroundTaskType.MARK_AS_COMPLETED:
                bgTaskName = nameof(MarkAsCompletedBackgroundTask);
                bgTaskType = typeof(MarkAsCompletedBackgroundTask);
                trigger    = new ToastNotificationActionTrigger();
                break;

            default:
                throw new ArgumentOutOfRangeException($"Provided bg task {backgroundTask} does not exists");
            }

            bool isBgTaskAlreadyRegistered = BackgroundTaskHelper.IsBackgroundTaskRegistered(bgTaskType);

            if (isBgTaskAlreadyRegistered && !restart)
            {
                return;
            }

            if (isBgTaskAlreadyRegistered)
            {
                UnregisterBackgroundTask(backgroundTask);
            }

            if (bgTaskInterval <= 0 && backgroundTask != BackgroundTaskType.MARK_AS_COMPLETED)
            {
                return;
            }

            BackgroundTaskHelper.Register(
                bgTaskName,
                trigger,
                false,
                true,
                conditions.ToArray());
        }
 public static void RegesterLiveTile(bool reg)
 {
     if (reg)
     {
         BackgroundTaskHelper.Register(typeof(LiveTileTask), new TimeTrigger(15, false), true);
     }
     else
     {
         BackgroundTaskHelper.Unregister(typeof(LiveTileTask));
     }
 }
Exemplo n.º 28
0
 /// <summary>
 /// Initializes a new instance for the <see cref="ArticleListViewModel" /> class.
 /// </summary>
 public SpeakersViewModel()
 {
     FeaturedStories            = new ObservableCollection <Speaker>();
     LatestStories              = new ObservableCollection <Speaker>();
     _speakerService            = new SpeakerService();
     _backgroundTaskHelper      = new BackgroundTaskHelper(GetSpeakers);
     this.MenuCommand           = new Command(this.MenuClicked);
     this.BookmarkCommand       = new Command(this.BookmarkButtonClicked);
     this.FeatureStoriesCommand = new Command(this.FeatureStoriesClicked);
     this.ItemSelectedCommand   = new Command(this.ItemSelected);
 }
Exemplo n.º 29
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (LocalSettingHelper.GetValue("EnableBackgroundTask") == "true")
            {
                BackgroundTaskHelper.RegisterBackgroundTask(DeviceKind.Windows);
            }

            Frame.BackStack.Clear();
        }
Exemplo n.º 30
0
        private async void Init()
        {
            await BackgroundTaskHelper.Register();

#if WINDOWS_APP
            Logger.LogAgent.GetInstance().Register("MS-UAP", "CNBlogs-Win8.1");
#endif
#if WINDOWS_PHONE_APP
            Logger.LogAgent.GetInstance().Register("MS-UAP", "CNBlogs-WP8.1");
#endif
        }