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; }
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); } } }
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); }