private async void LocationPanel_DeleteClick(object sender, RoutedEventArgs e) { FrameworkElement button = sender as FrameworkElement; if (button == null || (button != null && button.DataContext == null)) { return; } LocationPanelViewModel view = button.DataContext as LocationPanelViewModel; LocationData data = view.LocationData; // Remove location from list await Settings.DeleteLocation(data.query); // Remove panel LocationPanels.Remove(view); // Remove secondary tile if it exists if (SecondaryTileUtils.Exists(data.query)) { await new SecondaryTile( SecondaryTileUtils.GetTileId(data.query)).RequestDeleteAsync(); } }
private void CheckTiles() { var pinBtn = GetPinBtn(); pinBtn.IsEnabled = false; // Check if your app is currently pinned bool isPinned = SecondaryTileUtils.Exists(location.query); SetPinButton(isPinned); pinBtn.Visibility = Visibility.Visible; pinBtn.IsEnabled = true; }
private async Task <bool> UpdateLocation() { bool locationChanged = false; if (Settings.FollowGPS && (location == null || location.locationType == LocationType.GPS)) { Geoposition newGeoPos = null; try { newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10)); } catch (Exception) { var geoStatus = GeolocationAccessStatus.Unspecified; try { geoStatus = await Geolocator.RequestAccessAsync(); } catch (Exception ex) { Logger.WriteLine(LoggerLevel.Error, ex, "WeatherNow: GetWeather error"); } finally { if (geoStatus == GeolocationAccessStatus.Allowed) { try { newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10)); } catch (Exception ex) { Logger.WriteLine(LoggerLevel.Error, ex, "WeatherNow: GetWeather error"); } } else if (geoStatus == GeolocationAccessStatus.Denied) { // Disable gps feature Settings.FollowGPS = false; } } if (!Settings.FollowGPS) { return(false); } } // Access to location granted if (newGeoPos != null) { LocationData lastGPSLocData = await Settings.GetLastGPSLocData(); // Check previous location difference if (lastGPSLocData.query != null && geoPos != null && ConversionMethods.CalculateGeopositionDistance(geoPos, newGeoPos) < geolocal.MovementThreshold) { return(false); } if (lastGPSLocData.query != null && Math.Abs(ConversionMethods.CalculateHaversine(lastGPSLocData.latitude, lastGPSLocData.longitude, newGeoPos.Coordinate.Point.Position.Latitude, newGeoPos.Coordinate.Point.Position.Longitude)) < geolocal.MovementThreshold) { return(false); } LocationQueryViewModel view = null; await Task.Run(async() => { view = await wm.GetLocation(newGeoPos); if (String.IsNullOrEmpty(view.LocationQuery)) { view = new LocationQueryViewModel(); } }); if (String.IsNullOrWhiteSpace(view.LocationQuery)) { // Stop since there is no valid query return(false); } // Save oldkey string oldkey = lastGPSLocData.query; // Save location as last known lastGPSLocData.SetData(view, newGeoPos); Settings.SaveLastGPSLocData(lastGPSLocData); // Update tile id for location if (oldkey != null && SecondaryTileUtils.Exists(oldkey)) { await SecondaryTileUtils.UpdateTileId(oldkey, lastGPSLocData.query); } location = lastGPSLocData; geoPos = newGeoPos; locationChanged = true; } } return(locationChanged); }
public void OnWeatherLoaded(LocationData location, Weather weather) { // Save index before update int index = TextForecastControl.SelectedIndex; if (weather?.IsValid() == true) { wm.UpdateWeather(weather); WeatherView.UpdateView(weather); if (wm.SupportsAlerts) { if (weather.weather_alerts != null && weather.weather_alerts.Count > 0) { // Alerts are posted to the user here. Set them as notified. Task.Run(async() => { await WeatherAlertHandler.SetasNotified(location, weather.weather_alerts); }); } // Show/Hide Alert panel if (WeatherView.Extras.Alerts.Count > 0) { FrameworkElement alertButton = AlertButton; if (alertButton == null) { alertButton = FindName(nameof(AlertButton)) as FrameworkElement; } ResizeAlertPanel(); alertButton.Visibility = Visibility.Visible; } else { FrameworkElement alertButton = AlertButton; if (alertButton != null) { alertButton.Visibility = Visibility.Collapsed; } } } else { FrameworkElement alertButton = AlertButton; if (alertButton != null) { alertButton.Visibility = Visibility.Collapsed; } } // Update home tile if it hasn't been already if (Settings.HomeData.Equals(location) && (TimeSpan.FromTicks(DateTime.Now.Ticks - Settings.UpdateTime.Ticks).TotalMinutes > Settings.RefreshInterval) || !WeatherTileCreator.TileUpdated) { Task.Run(async() => await WeatherUpdateBackgroundTask.RequestAppTrigger()); } else if (SecondaryTileUtils.Exists(location.query)) { WeatherTileCreator.TileUpdater(location, weather); } // Shell Shell.Instance.HamburgerButtonColor = WeatherView.PendingBackgroundColor; if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar")) { // Mobile StatusBar.GetForCurrentView().BackgroundColor = WeatherView.PendingBackgroundColor; } else { // Desktop var titlebar = ApplicationView.GetForCurrentView().TitleBar; titlebar.BackgroundColor = WeatherView.PendingBackgroundColor; titlebar.ButtonBackgroundColor = titlebar.BackgroundColor; } } // Set saved index from before update // Note: needed since ItemSource is cleared and index is reset if (index == 0) // Note: UWP Mobile Bug { TextForecastControl.SelectedIndex = index + 1; } TextForecastControl.SelectedIndex = index; if (WeatherView.Extras.HourlyForecast.Count >= 1) { HourlyForecastPanel.Visibility = Visibility.Visible; } else { HourlyForecastPanel.Visibility = Visibility.Collapsed; } if (WeatherView.Extras.TextForecast.Count >= 1) { ForecastSwitch.Visibility = Visibility.Visible; } else { ForecastSwitch.Visibility = Visibility.Collapsed; } if (!String.IsNullOrWhiteSpace(WeatherView.Extras.Chance)) { if (!Settings.API.Equals(WeatherAPI.MetNo)) { if (!DetailsWrapGrid.Children.Contains(PrecipitationPanel)) { DetailsWrapGrid.Children.Insert(0, PrecipitationPanel); ResizeDetailItems(); } PrecipitationPanel.Visibility = Visibility.Visible; } else { DetailsWrapGrid.Children.Remove(PrecipitationPanel); ResizeDetailItems(); } int precipCount = PrecipitationPanel.Children.Count; int atmosCount = AtmospherePanel.Children.Count; if (Settings.API.Equals(WeatherAPI.OpenWeatherMap) || Settings.API.Equals(WeatherAPI.MetNo)) { if (ChanceItem != null) { PrecipitationPanel.Children.Remove(ChanceItem); } FrameworkElement cloudinessItem = CloudinessItem; if (cloudinessItem == null) { cloudinessItem = FindName(nameof(CloudinessItem)) as FrameworkElement; } if (cloudinessItem != null && !AtmospherePanel.Children.Contains(cloudinessItem)) { AtmospherePanel.Children.Insert(2, cloudinessItem); } } else { FrameworkElement chanceItem = ChanceItem; if (chanceItem == null) { chanceItem = FindName(nameof(ChanceItem)) as FrameworkElement; } if (chanceItem != null && !PrecipitationPanel.Children.Contains(chanceItem)) { PrecipitationPanel.Children.Insert(2, chanceItem); } if (CloudinessItem != null) { AtmospherePanel.Children.Remove(CloudinessItem); } } if (precipCount != PrecipitationPanel.Children.Count || atmosCount != AtmospherePanel.Children.Count) { ResizeDetailItems(); } } else { DetailsWrapGrid.Children.Remove(PrecipitationPanel); if (CloudinessItem != null) { AtmospherePanel.Children.Remove(CloudinessItem); } ResizeDetailItems(); } LoadingRing.IsActive = false; }
private async void PinButton_Click(object sender, RoutedEventArgs e) { var pinBtn = sender as AppBarButton; pinBtn.IsEnabled = false; if (SecondaryTileUtils.Exists(location.query)) { bool deleted = await new SecondaryTile( SecondaryTileUtils.GetTileId(location.query)).RequestDeleteAsync(); if (deleted) { SecondaryTileUtils.RemoveTileId(location.query); } SetPinButton(!deleted); GetPinBtn().IsEnabled = true; } else { // Initialize the tile with required arguments var tileID = DateTime.Now.Ticks.ToString(); var tile = new SecondaryTile( tileID, "SimpleWeather", "action=view-weather&query=" + location.query, new Uri("ms-appx:///Assets/Square150x150Logo.png"), TileSize.Default); // Enable wide and large tile sizes tile.VisualElements.Wide310x150Logo = new Uri("ms-appx:///Assets/Wide310x150Logo.png"); tile.VisualElements.Square310x310Logo = new Uri("ms-appx:///Assets/Square310x310Logo.png"); // Add a small size logo for better looking small tile tile.VisualElements.Square71x71Logo = new Uri("ms-appx:///Assets/Square71x71Logo.png"); // Add a unique corner logo for the secondary tile tile.VisualElements.Square44x44Logo = new Uri("ms-appx:///Assets/Square44x44Logo.png"); // Show the display name on all sizes tile.VisualElements.ShowNameOnSquare150x150Logo = true; tile.VisualElements.ShowNameOnWide310x150Logo = true; tile.VisualElements.ShowNameOnSquare310x310Logo = true; bool isPinned = await tile.RequestCreateAsync(); if (isPinned) { // Update tile with notifications SecondaryTileUtils.AddTileId(location.query, tileID); await WeatherTileCreator.TileUpdater(location); await tile.UpdateAsync(); } SetPinButton(isPinned); GetPinBtn().IsEnabled = true; } }
private async void FollowGPS_Toggled(object sender, RoutedEventArgs e) { ToggleSwitch sw = sender as ToggleSwitch; if (sw.IsOn) { var geoStatus = GeolocationAccessStatus.Unspecified; try { // Catch error in case dialog is dismissed geoStatus = await Geolocator.RequestAccessAsync(); } catch (Exception ex) { Logger.WriteLine(LoggerLevel.Error, ex, "SettingsPage: error getting location permission"); } // Setup error just in case MessageDialog error = null; switch (geoStatus) { case GeolocationAccessStatus.Allowed: // Reset home location data //Settings.SaveLastGPSLocData(new WeatherData.LocationData()); break; case GeolocationAccessStatus.Denied: error = new MessageDialog(App.ResLoader.GetString("Msg_LocDeniedSettings"), App.ResLoader.GetString("Label_ErrLocationDenied")); error.Commands.Add(new UICommand(App.ResLoader.GetString("Label_Settings"), async(command) => { await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location")); }, 0)); error.Commands.Add(new UICommand(App.ResLoader.GetString("Label_Cancel"), null, 1)); error.DefaultCommandIndex = 0; error.CancelCommandIndex = 1; await error.ShowAsync(); sw.IsOn = false; break; case GeolocationAccessStatus.Unspecified: error = new MessageDialog(App.ResLoader.GetString("Error_Location"), App.ResLoader.GetString("Label_ErrorLocation")); await error.ShowAsync(); sw.IsOn = false; break; default: break; } } // Update ids when switching GPS feature if (sw.IsOn) { var prevLoc = (await Settings.GetFavorites()).FirstOrDefault(); if (prevLoc?.query != null && SecondaryTileUtils.Exists(prevLoc.query)) { var gpsLoc = await Settings.GetLastGPSLocData(); if (gpsLoc?.query == null) { Settings.SaveLastGPSLocData(prevLoc); } else { await SecondaryTileUtils.UpdateTileId(prevLoc.query, gpsLoc.query); } } } else { var prevLoc = await Settings.GetLastGPSLocData(); if (prevLoc?.query != null && SecondaryTileUtils.Exists(prevLoc.query)) { var favLoc = (await Settings.GetFavorites()).FirstOrDefault(); if (favLoc?.query != null) { await SecondaryTileUtils.UpdateTileId(prevLoc.query, favLoc.query); } } } Settings.FollowGPS = sw.IsOn; RequestAppTrigger = true; }
/// <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 void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { //this.DebugSettings.EnableFrameRateCounter = true; } #endif Logger.WriteLine(LoggerLevel.Info, "Started logger..."); var Dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher; // App loaded for first time Initialize(e).ContinueWith(async(t) => { if (!e.PrelaunchActivated) { if (Settings.WeatherLoaded && !String.IsNullOrEmpty(e.TileId) && !e.TileId.Equals("App", StringComparison.OrdinalIgnoreCase)) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if (RootFrame.Content == null) { RootFrame.Navigate(typeof(Shell), "suppressNavigate"); } }); // Navigate to WeatherNow page for location if (Shell.Instance != null) { var locData = Task.Run(Settings.GetLocationData).Result; var locations = new List <LocationData>(locData) { Settings.HomeData, }; var location = locations.FirstOrDefault(loc => loc.query.Equals(SecondaryTileUtils.GetQueryFromId(e.TileId))); if (location != null) { var isHome = location.Equals(Settings.HomeData); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Shell.Instance.AppFrame.Navigate(typeof(WeatherNow), location); Shell.Instance.AppFrame.BackStack.Clear(); if (!isHome) { Shell.Instance.AppFrame.BackStack.Add(new PageStackEntry(typeof(WeatherNow), null, null)); SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible; } else { SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed; } }); } // If Shell content is empty navigate to default page await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if (Shell.Instance.AppFrame.CurrentSourcePageType == null) { Shell.Instance.AppFrame.Navigate(typeof(WeatherNow), null); } }); } } await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if (RootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (Settings.WeatherLoaded) { RootFrame.Navigate(typeof(Shell), e.Arguments); } else { RootFrame.Navigate(typeof(SetupPage), e.Arguments); } } // Ensure the current window is active Window.Current.Activate(); }); } }); }
private async Task LoadWeatherData() { /* * If unable to retrieve saved data, data is old, or units don't match * Refresh weather data */ Logger.WriteLine(LoggerLevel.Debug, "{0}: Loading weather data for {1}", TAG, location?.ToString()); bool gotData = await LoadSavedWeatherData(); if (!gotData) { Logger.WriteLine(LoggerLevel.Debug, "{0}: Saved weather data invalid for {1}", TAG, location?.ToString()); Logger.WriteLine(LoggerLevel.Debug, "{0}: Retrieving data from weather provider", TAG); try { if ((weather != null && weather.source != Settings.API) || (weather == null && location != null && location.source != Settings.API)) { // Update location query and source for new API string oldKey = location.query; if (weather != null) { location.query = await wm.UpdateLocationQuery(weather); } else { location.query = await wm.UpdateLocationQuery(location); } location.source = Settings.API; // Update database as well #if !__ANDROID_WEAR__ if (location.locationType == LocationType.GPS) { Settings.SaveLastGPSLocData(location); #if __ANDROID__ WearableDataListenerService.EnqueueWork(App.Context, new Android.Content.Intent(App.Context, typeof(WearableDataListenerService)) .SetAction(WearableDataListenerService.ACTION_SENDLOCATIONUPDATE)); #endif } else { await Settings.UpdateLocationWithKey(location, oldKey); } #else Settings.SaveHomeData(location); #endif #if WINDOWS_UWP // Update tile id for location if (SecondaryTileUtils.Exists(oldKey)) { await SecondaryTileUtils.UpdateTileId(oldKey, location.query); } #elif __ANDROID__ && !__ANDROID_WEAR__ if (WidgetUtils.Exists(oldKey)) { WidgetUtils.UpdateWidgetIds(oldKey, location); } #endif } await GetWeatherData(); } catch (WeatherException wEx) { errorCallback?.OnWeatherError(wEx); } } }
public void Run(IBackgroundTaskInstance taskInstance) { // Get a deferral, to prevent the task from closing prematurely // while asynchronous code is still running. var deferral = taskInstance.GetDeferral(); taskInstance.Canceled += OnCanceled; Task.Run(async() => { try { Logger.WriteLine(LoggerLevel.Debug, "WeatherUpdateBackgroundTask: Run..."); if (Settings.WeatherLoaded) { Logger.WriteLine(LoggerLevel.Debug, "WeatherUpdateBackgroundTask: Getting weather data..."); // Retrieve weather data. var weather = await GetWeather(); if (cts.IsCancellationRequested) { return; } // Update the live tile with data. Logger.WriteLine(LoggerLevel.Debug, "WeatherUpdateBackgroundTask: Weather is NULL = " + (weather == null).ToString()); Logger.WriteLine(LoggerLevel.Debug, "WeatherUpdateBackgroundTask: Updating primary tile..."); if (weather != null) { WeatherTileCreator.TileUpdater(Settings.HomeData, weather); } if (cts.IsCancellationRequested) { return; } // Update secondary tiles var tiles = await SecondaryTile.FindAllAsync(); foreach (SecondaryTile tile in tiles) { Logger.WriteLine(LoggerLevel.Debug, "WeatherUpdateBackgroundTask: Updating secondary tile..."); var locations = await Settings.GetLocationData(); var location = locations.FirstOrDefault( loc => loc.query.Equals(SecondaryTileUtils.GetQueryFromId(tile.TileId))); Logger.WriteLine(LoggerLevel.Debug, "Location = " + location?.name); Logger.WriteLine(LoggerLevel.Debug, "TileID = " + tile.TileId); if (location != null) { await WeatherTileCreator.TileUpdater(location); } if (cts.IsCancellationRequested) { return; } } // Post alerts if setting is on Logger.WriteLine(LoggerLevel.Debug, "WeatherUpdateBackgroundTask: Posting alerts..."); if (Settings.ShowAlerts && wm.SupportsAlerts && weather != null) { await WeatherAlertHandler.PostAlerts(Settings.HomeData, weather.weather_alerts); } if (cts.IsCancellationRequested) { return; } // Set update time if (weather != null) { Settings.UpdateTime = DateTime.Now; } } Logger.WriteLine(LoggerLevel.Debug, "WeatherUpdateBackgroundTask: End of run..."); } catch (Exception ex) { Logger.WriteLine(LoggerLevel.Error, ex, "{0}: exception occurred...", taskName); } }).ContinueWith((t) => { // Inform the system that the task is finished. deferral.Complete(); cts.Dispose(); }); }
private async Task <bool> UpdateLocation() { bool locationChanged = false; if (Settings.FollowGPS) { Geoposition newGeoPos = null; Geolocator geolocal = new Geolocator() { DesiredAccuracyInMeters = 5000, ReportInterval = 900000, MovementThreshold = 1600 }; try { cts.Token.ThrowIfCancellationRequested(); newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10)).AsTask(cts.Token); } catch (OperationCanceledException) { return(locationChanged); } catch (Exception) { var geoStatus = GeolocationAccessStatus.Unspecified; try { cts.Token.ThrowIfCancellationRequested(); geoStatus = await Geolocator.RequestAccessAsync().AsTask(cts.Token); } catch (OperationCanceledException) { return(locationChanged); } catch (Exception ex) { Logger.WriteLine(LoggerLevel.Error, ex, "{0}: error requesting location permission", taskName); } finally { if (!cts.IsCancellationRequested && geoStatus == GeolocationAccessStatus.Allowed) { try { newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10)).AsTask(cts.Token); } catch (Exception ex) { Logger.WriteLine(LoggerLevel.Error, ex, "{0}: GetWeather error", taskName); } } } } // Access to location granted if (newGeoPos != null) { var lastGPSLocData = await Settings.GetLastGPSLocData(); if (cts.IsCancellationRequested) { return(locationChanged); } // Check previous location difference if (lastGPSLocData.query != null && Math.Abs(ConversionMethods.CalculateHaversine(lastGPSLocData.latitude, lastGPSLocData.longitude, newGeoPos.Coordinate.Point.Position.Latitude, newGeoPos.Coordinate.Point.Position.Longitude)) < geolocal.MovementThreshold) { return(false); } LocationQueryViewModel view = null; await Task.Run(async() => { view = await wm.GetLocation(newGeoPos); if (String.IsNullOrEmpty(view.LocationQuery)) { view = new LocationQueryViewModel(); } }, cts.Token); if (String.IsNullOrWhiteSpace(view.LocationQuery)) { // Stop since there is no valid query return(false); } if (cts.IsCancellationRequested) { return(locationChanged); } // Save oldkey string oldkey = lastGPSLocData.query; // Save location as last known lastGPSLocData.SetData(view, newGeoPos); Settings.SaveLastGPSLocData(lastGPSLocData); // Update tile id for location if (oldkey != null && SecondaryTileUtils.Exists(oldkey)) { await SecondaryTileUtils.UpdateTileId(oldkey, lastGPSLocData.query); } locationChanged = true; } } return(locationChanged); }