private async Task LoadGPSPanel() { if (Settings.FollowGPS) { GPSPanel.Visibility = Visibility.Visible; var locData = await Settings.GetLastGPSLocData(); if (locData == null || locData.query == null) { locData = await UpdateLocation(); } if (locData != null && locData.query != null) { var panel = new LocationPanelViewModel() { LocationData = locData }; GPSPanelViewModel[0] = panel; var wLoader = new WeatherDataLoader(locData, this, this); await wLoader.LoadWeatherData(false); } } }
private async Task LoadGPSPanel() { // Setup gps panel if (Settings.FollowGPS) { AppCompatActivity?.RunOnUiThread(() => { gpsPanelLayout.Visibility = ViewStates.Visible; }); var locData = await Settings.GetLastGPSLocData(); if (locData == null || locData.query == null) { locData = await UpdateLocation(); } if (locData != null && locData.query != null) { gpsPanelViewModel = new LocationPanelViewModel() { LocationData = locData }; #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed Task.Run(async() => { var wLoader = new WeatherDataLoader(locData, this, this); await wLoader.LoadWeatherData(false); }); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } } }
private async Task CancelDataSync() { if (timer.Enabled) { timer.Stop(); } if (Settings.DataSync == WearableDataSync.DeviceOnly) { if (location == null && Settings.HomeData != null) { // Load whatever we have available location = Settings.HomeData; wLoader = new WeatherDataLoader(location, this, this); await wLoader.ForceLoadSavedWeatherData(); } else { Activity?.RunOnUiThread(() => { Toast.MakeText(Activity, GetString(Resource.String.werror_noweather), ToastLength.Long).Show(); }); } } }
private async Task LoadLocations() { // Disable EditMode button EditButton.IsEnabled = false; // Lets load it up... var locations = await Settings.GetFavorites(); LocationPanels.Clear(); // Setup saved favorite locations await LoadGPSPanel(); foreach (LocationData location in locations) { var panel = new LocationPanelViewModel() { // Save index to tag (to easily retreive) LocationData = location }; LocationPanels.Add(panel); } foreach (LocationData location in locations) { var wLoader = new WeatherDataLoader(location, this, this); await wLoader.LoadWeatherData(false); } // Enable EditMode button EditButton.IsEnabled = true; }
private async Task <Weather> GetWeather() { Weather weather = null; try { if (Settings.DataSync == WearableDataSync.Off && Settings.FollowGPS) { await UpdateLocation(); } var wloader = new WeatherDataLoader(Settings.HomeData); if (Settings.DataSync == WearableDataSync.Off) { await wloader.LoadWeatherData(false); } else { await wloader.ForceLoadSavedWeatherData(); } locData = Settings.HomeData; weather = wloader.GetWeather(); } catch (Exception ex) { Logger.WriteLine(LoggerLevel.Error, ex, "SimpleWeather: {0}: GetWeather: error", TAG); } return(weather); }
private async Task LoadLocations() { // Load up saved locations var locations = await Settings.GetFavorites(); AppCompatActivity?.RunOnUiThread(() => mAdapter.RemoveAll()); // Setup saved favorite locations await LoadGPSPanel(); foreach (LocationData location in locations) { var panel = new LocationPanelViewModel() { LocationData = location }; AppCompatActivity?.RunOnUiThread(() => mAdapter.Add(panel)); } foreach (LocationData location in locations) { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed Task.Run(async() => { var wLoader = new WeatherDataLoader(location, this, this); await wLoader.LoadWeatherData(false); }); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } }
private async Task <Weather> GetWeather() { Weather weather = null; try { if (Settings.FollowGPS) { await UpdateLocation(); } cts.Token.ThrowIfCancellationRequested(); var wloader = new WeatherDataLoader(Settings.HomeData); await wloader.LoadWeatherData(false); weather = wloader.GetWeather(); } catch (OperationCanceledException cancelEx) { Logger.WriteLine(LoggerLevel.Info, cancelEx, "{0}: GetWeather cancelled", taskName); return(null); } catch (Exception ex) { Logger.WriteLine(LoggerLevel.Error, ex, "{0}: GetWeather error", taskName); return(null); } return(weather); }
private async Task Resume() { // Save index before update int index = TextForecastControl.SelectedIndex; // Check pin tile status CheckTiles(); if (wLoader.GetWeather()?.IsValid() == true) { Weather weather = wLoader.GetWeather(); // Update weather if needed on resume if (Settings.FollowGPS && await UpdateLocation()) { // Setup loader from updated location wLoader = new WeatherDataLoader(location, this, this); await RefreshWeather(false); } else { // Check weather data expiration if (!int.TryParse(weather.ttl, out int ttl)) { ttl = Settings.DefaultInterval; } TimeSpan span = DateTimeOffset.Now - weather.update_time; if (span.TotalMinutes > ttl) { await RefreshWeather(false); } else { WeatherView.UpdateView(wLoader.GetWeather()); 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; }
private async Task Resume() { /* Update view on resume * ex. If temperature unit changed */ // New Page = loaded - true // Navigating back to frag = !loaded - false if (loaded || wLoader == null) { await Restore(); loaded = true; } else if (wLoader != null && !loaded) { var culture = System.Globalization.CultureInfo.CurrentCulture; var locale = wm.LocaleToLangCode(culture.TwoLetterISOLanguageName, culture.Name); // Reset if source || locale is different if (weatherView.WeatherSource != Settings.API || wm.SupportsWeatherLocale && weatherView.WeatherLocale != locale) { await Restore(); loaded = true; } else if (wLoader.GetWeather()?.IsValid() == true) { var weather = wLoader.GetWeather(); // Update weather if needed on resume if (Settings.FollowGPS && await UpdateLocation()) { // Setup loader from updated location wLoader = new WeatherDataLoader(this.location, this, this); await RefreshWeather(false); loaded = true; } else { // Check weather data expiration TimeSpan span = DateTimeOffset.Now - weather.update_time; if (span.TotalMinutes > Settings.DefaultInterval) { await RefreshWeather(false); } else { weatherView.UpdateView(wLoader.GetWeather()); SetView(weatherView); mCallback?.OnWeatherViewUpdated(weatherView); loaded = true; } } } } }
public static async Task TileUpdater(LocationData location) { var wloader = new WeatherDataLoader(location); await wloader.LoadWeatherData(false); if (wloader.GetWeather() != null) { TileUpdater(location, wloader.GetWeather()); } }
private async void RefreshButton_Click(object sender, RoutedEventArgs e) { if (Settings.FollowGPS && await UpdateLocation()) { // Setup loader from updated location wLoader = new WeatherDataLoader(location, this, this); } await RefreshWeather(true); }
private async Task Restore() { bool forceRefresh = false; // GPS Follow location if (Settings.FollowGPS && (location == null || location.locationType == LocationType.GPS)) { LocationData locData = await Settings.GetLastGPSLocData(); if (locData == null) { // Update location if not setup await UpdateLocation(); wLoader = new WeatherDataLoader(location, this, this); forceRefresh = true; } else { // Reset locdata if source is different if (locData.source != Settings.API) { Settings.SaveLastGPSLocData(new LocationData()); } if (await UpdateLocation()) { // Setup loader from updated location wLoader = new WeatherDataLoader(location, this, this); forceRefresh = true; } else { // Setup loader saved location data location = locData; wLoader = new WeatherDataLoader(location, this, this); } } } // Regular mode else if (wLoader == null) { // Weather was loaded before. Lets load it up... location = Settings.HomeData; wLoader = new WeatherDataLoader(location, this, this); } // Check pin tile status CheckTiles(); // Load up weather data await RefreshWeather(forceRefresh); }
public static void autoRefresh(Object obj) { WeatherDataLoader loader = obj as WeatherDataLoader; while (true) { Thread.Sleep(5 * 1000); if (loader.SelectedCity != null) { loader.refreshWeatherData(loader.SelectedCity.id.ToString()); loader.OnPropertyChanged("Weather"); loader.RefreshMessage = "Last time updated: " + DateTime.Now.ToString(); } } }
private async Task RefreshLocations() { // Reload all panels if needed var locations = await Settings.GetLocationData(); var homeData = await Settings.GetLastGPSLocData(); bool reload = (locations.Count != mAdapter.ItemCount || Settings.FollowGPS && gpsPanelViewModel == null); // Reload if weather source differs if ((gpsPanelViewModel != null && gpsPanelViewModel.WeatherSource != Settings.API) || (mAdapter.ItemCount >= 1 && mAdapter.Dataset[0].WeatherSource != Settings.API)) { reload = true; } // Reload if panel queries dont match if (!reload && (gpsPanelViewModel != null && homeData.query != gpsPanelViewModel.LocationData.query)) { reload = true; } if (reload) { AppCompatActivity?.RunOnUiThread(() => mAdapter.RemoveAll()); await LoadLocations(); } else { var dataset = mAdapter.Dataset; if (gpsPanelViewModel != null) { dataset.Add(gpsPanelViewModel); } foreach (LocationPanelViewModel view in dataset) { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed Task.Run(async() => { var wLoader = new WeatherDataLoader(view.LocationData, this, this); await wLoader.LoadWeatherData(false); }); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } } }
private async Task RefreshLocations() { // Disable EditMode button EditButton.IsEnabled = false; // Reload all panels if needed var locations = await Settings.GetLocationData(); var homeData = await Settings.GetLastGPSLocData(); bool reload = (locations.Count != LocationPanels.Count || (Settings.FollowGPS && (GPSPanelViewModel.First() == null))); // Reload if weather source differs if ((GPSPanelViewModel.First() != null && GPSPanelViewModel.First().WeatherSource != Settings.API) || (LocationPanels.Count >= 1 && LocationPanels[0].WeatherSource != Settings.API)) { reload = true; } // Reload if panel queries dont match if (!reload && (GPSPanelViewModel.First() != null && homeData.query != GPSPanelViewModel.First().LocationData.query)) { reload = true; } if (reload) { LocationPanels.Clear(); await LoadLocations(); } else { var dataset = LocationPanels.ToList(); if (GPSPanelViewModel.First() != null) { dataset.Add(GPSPanelViewModel.First()); } foreach (LocationPanelViewModel view in dataset) { var wLoader = new WeatherDataLoader(view.LocationData, this, this); await wLoader.LoadWeatherData(false); } } // Enable EditMode button EditButton.IsEnabled = true; }
public MainWindow() { InitializeComponent(); this.Height = (System.Windows.SystemParameters.PrimaryScreenHeight * 0.7); this.Width = (System.Windows.SystemParameters.PrimaryScreenWidth * 0.7); loader.readCitiesFromJson(); CityDescriptor currentCity = WeatherDataLoader.getCurrentLocation(); loader.selectCity(currentCity); loader.refreshWeatherData(loader.SelectedCity.id.ToString()); loader.SelectedDay = loader.Weather.DayForecasts[0]; DateTime dt = DateTime.Now; loader.RefreshMessage = "Last time updated: " + dt.ToString(); loader.loadFavouriteCities(); CheckFavourite(); refresher.Start(loader); this.DataContext = loader; }
public void OnSharedPreferenceChanged(ISharedPreferences sharedPreferences, string key) { if (String.IsNullOrWhiteSpace(key)) { return; } switch (key) { case "key_datasync": // If data sync settings changes, // reset so we can properly reload wLoader = null; location = null; break; default: break; } }
public override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your fragment here if (Arguments != null) { using (var jsonTextReader = new Newtonsoft.Json.JsonTextReader( new System.IO.StringReader(Arguments.GetString("data", null)))) { location = LocationData.FromJson(jsonTextReader); } if (location != null && wLoader == null) { wLoader = new WeatherDataLoader(location, this, this); } } if (savedInstanceState != null) { BGAlpha = savedInstanceState.GetInt("alpha", 255); } mLocListnr = new LocationListener(); mLocListnr.LocationChanged += async(Android.Locations.Location location) => { if (Settings.FollowGPS && await UpdateLocation()) { // Setup loader from updated location wLoader = new WeatherDataLoader(this.location, this, this); await RefreshWeather(false); } }; loaded = true; }
private async Task DataSyncResume() { if (!receiverRegistered) { IntentFilter filter = new IntentFilter(); filter.AddAction(WearableHelper.SettingsPath); filter.AddAction(WearableHelper.LocationPath); filter.AddAction(WearableHelper.WeatherPath); filter.AddAction(WearableHelper.IsSetupPath); LocalBroadcastManager.GetInstance(Activity) .RegisterReceiver(dataReceiver, filter); receiverRegistered = true; } /* Update view on resume * ex. If temperature unit changed */ // New Page = loaded - true // Navigating back to frag = !loaded - false if (loaded || wLoader == null) { DataSyncRestore(); } else if (wLoader != null && !loaded) { if (wLoader.GetWeather()?.IsValid() == true) { Weather weather = wLoader.GetWeather(); /* * DateTime < 0 - This instance is earlier than value. * DateTime == 0 - This instance is the same as value. * DateTime > 0 - This instance is later than value. */ if (Settings.UpdateTime.CompareTo(weather.update_time.UtcDateTime) > 0) { // Data was updated while we we're away; loaded it up if (location == null || !location.Equals(Settings.HomeData)) { location = Settings.HomeData; } Activity?.RunOnUiThread(() => refreshLayout.Refreshing = true); wLoader = new WeatherDataLoader(this.location, this, this); await wLoader.ForceLoadSavedWeatherData(); } else { // Check weather data expiration TimeSpan span = DateTimeOffset.Now - weather.update_time; if (span.TotalMinutes > Settings.DefaultInterval) { // send request to refresh data on connected device Activity?.StartService(new Intent(Activity, typeof(WearableDataListenerService)) .SetAction(WearableDataListenerService.ACTION_REQUESTWEATHERUPDATE) .PutExtra(WearableDataListenerService.EXTRA_FORCEUPDATE, true)); } weatherView.UpdateView(wLoader.GetWeather()); SetView(weatherView); mCallback?.OnWeatherViewUpdated(weatherView); loaded = true; } } else { // Data is null; restore DataSyncRestore(); } } }
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.Inflate(Resource.Layout.fragment_weather_now, container, false); // Setup Actionbar HasOptionsMenu = false; refreshLayout = (SwipeRefreshLayout)view; mainView = view.FindViewById <NestedScrollView>(Resource.Id.fragment_weather_now); mainView.ScrollChange += ScrollView_ScrollChange; bgImageView = view.FindViewById <ImageView>(Resource.Id.image_view); // Condition locationName = view.FindViewById <TextView>(Resource.Id.label_location_name); updateTime = view.FindViewById <TextView>(Resource.Id.label_updatetime); weatherIcon = view.FindViewById <TextView>(Resource.Id.weather_icon); weatherCondition = view.FindViewById <TextView>(Resource.Id.weather_condition); weatherTemp = view.FindViewById <TextView>(Resource.Id.weather_temp); // Details detailsPanel = view.FindViewById(Resource.Id.details_panel); humidity = view.FindViewById <TextView>(Resource.Id.humidity); pressureState = view.FindViewById <TextView>(Resource.Id.pressure_state); pressure = view.FindViewById <TextView>(Resource.Id.pressure); visiblity = view.FindViewById <TextView>(Resource.Id.visibility_val); feelslike = view.FindViewById <TextView>(Resource.Id.feelslike); windDirection = view.FindViewById <TextView>(Resource.Id.wind_direction); windSpeed = view.FindViewById <TextView>(Resource.Id.wind_speed); sunrise = view.FindViewById <TextView>(Resource.Id.sunrise_time); sunset = view.FindViewById <TextView>(Resource.Id.sunset_time); // Forecast forecastPanel = view.FindViewById <RelativeLayout>(Resource.Id.forecast_panel); forecastPanel.Visibility = ViewStates.Invisible; forecastView = view.FindViewById <Android.Support.V7.Widget.RecyclerView>(Resource.Id.forecast_view); // Additional Details forecastSwitch = view.FindViewById <Switch>(Resource.Id.forecast_switch); forecastSwitch.CheckedChange += ForecastSwitch_CheckedChange; forecastSwitch.Visibility = ViewStates.Gone; txtForecastView = view.FindViewById <ViewPager>(Resource.Id.txt_forecast_viewpgr); txtForecastView.Adapter = new TextForecastPagerAdapter(this.Activity, new List <TextForecastItemViewModel>()); txtForecastView.Visibility = ViewStates.Gone; hrforecastPanel = view.FindViewById <LinearLayout>(Resource.Id.hourly_forecast_panel); hrforecastPanel.Visibility = ViewStates.Gone; hrforecastView = view.FindViewById <Android.Support.V7.Widget.RecyclerView>(Resource.Id.hourly_forecast_view); precipitationPanel = view.FindViewById <RelativeLayout>(Resource.Id.precipitation_card); precipitationPanel.Visibility = ViewStates.Gone; chanceLabel = view.FindViewById <TextView>(Resource.Id.chance_label); chance = view.FindViewById <TextView>(Resource.Id.chance_val); cloudinessLabel = view.FindViewById <TextView>(Resource.Id.cloudiness_label); cloudiness = view.FindViewById <TextView>(Resource.Id.cloudiness); qpfRain = view.FindViewById <TextView>(Resource.Id.qpf_rain_val); qpfSnow = view.FindViewById <TextView>(Resource.Id.qpf_snow_val); // Alerts alertButton = view.FindViewById(Resource.Id.alert_button); alertButton.Click += (sender, e) => { // Show Alert Fragment if (weatherView.Extras.Alerts.Count > 0) { AppCompatActivity.SupportFragmentManager.BeginTransaction() .Add(Resource.Id.fragment_container, WeatherAlertsFragment.NewInstance(location, weatherView)) .Hide(this) .AddToBackStack(null) .Commit(); } }; alertButton.Visibility = ViewStates.Invisible; // Cloudiness only supported by OWM cloudinessLabel.Visibility = ViewStates.Gone; cloudiness.Visibility = ViewStates.Gone; forecastView.HasFixedSize = true; forecastAdapter = new ForecastItemAdapter(new List <ForecastItemViewModel>()); forecastView.SetAdapter(forecastAdapter); hrforecastView.HasFixedSize = true; hrforecastAdapter = new HourlyForecastItemAdapter(new List <HourlyForecastItemViewModel>()); hrforecastView.SetAdapter(hrforecastAdapter); // SwipeRefresh refreshLayout.SetColorSchemeColors(ContextCompat.GetColor(Activity, Resource.Color.colorPrimary)); refreshLayout.Refresh += delegate { Task.Run(async() => { if (Settings.FollowGPS && await UpdateLocation()) { // Setup loader from updated location wLoader = new WeatherDataLoader(this.location, this, this); } await RefreshWeather(true); }); }; // Nav Header View navheader = Activity.FindViewById <NavigationView>(Resource.Id.nav_view).GetHeaderView(0); navLocation = navheader.FindViewById <TextView>(Resource.Id.nav_location); navWeatherTemp = navheader.FindViewById <TextView>(Resource.Id.nav_weathertemp); weatherCredit = view.FindViewById <TextView>(Resource.Id.weather_credit); loaded = true; refreshLayout.Refreshing = true; return(view); }
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.Inflate(Resource.Layout.fragment_weather_now, container, false); view.FocusableInTouchMode = true; view.GenericMotion += (sender, e) => { if (e.Event.Action == MotionEventActions.Scroll && RotaryEncoder.IsFromRotaryEncoder(e.Event)) { // Don't forget the negation here float delta = -RotaryEncoder.GetRotaryAxisValue(e.Event) * RotaryEncoder.GetScaledScrollFactor(Activity); // Swap these axes if you want to do horizontal scrolling instead scrollView.ScrollBy(0, (int)Math.Round(delta)); e.Handled = true; } e.Handled = false; }; refreshLayout = (SwipeRefreshLayout)view; scrollView = view.FindViewById <NestedScrollView>(Resource.Id.fragment_weather_now); // Condition locationName = view.FindViewById <TextView>(Resource.Id.label_location_name); updateTime = view.FindViewById <TextView>(Resource.Id.label_updatetime); weatherIcon = view.FindViewById <TextView>(Resource.Id.weather_icon); weatherCondition = view.FindViewById <TextView>(Resource.Id.weather_condition); weatherTemp = view.FindViewById <TextView>(Resource.Id.weather_temp); // SwipeRefresh refreshLayout.SetColorSchemeColors(ContextCompat.GetColor(Activity, Resource.Color.colorPrimary)); refreshLayout.Refresh += delegate { Task.Run(async() => { if (Settings.FollowGPS && await UpdateLocation()) { // Setup loader from updated location wLoader = new WeatherDataLoader(this.location, this, this); } await RefreshWeather(true); }); }; weatherCredit = view.FindViewById <TextView>(Resource.Id.weather_credit); loaded = true; refreshLayout.Refreshing = true; timer = new System.Timers.Timer(30000); // 30sec timer.Elapsed += async(sender, e) => { // We hit the interval // Data syncing is taking a long time to setup // Stop and load saved data await CancelDataSync(); }; return(view); }
public override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your fragment here if (Arguments != null) { using (var jsonTextReader = new Newtonsoft.Json.JsonTextReader( new System.IO.StringReader(Arguments.GetString("data", null)))) { location = LocationData.FromJson(jsonTextReader); } if (location != null && wLoader == null) { wLoader = new WeatherDataLoader(location, this, this); } } if (WearableHelper.IsGooglePlayServicesInstalled && !WearableHelper.HasGPS) { mFusedLocationClient = new FusedLocationProviderClient(Activity); mLocCallback = new LocationCallback(); mLocCallback.LocationResult += async(sender, e) => { mLocation = e.Result.LastLocation; if (Settings.FollowGPS && await UpdateLocation()) { // Setup loader from updated location wLoader = new WeatherDataLoader(this.location, this, this); await RefreshWeather(false); } await mFusedLocationClient.RemoveLocationUpdatesAsync(mLocCallback); }; } else { mLocListnr = new Droid.Helpers.LocationListener(); mLocListnr.LocationChanged += async(Android.Locations.Location location) => { if (Settings.FollowGPS && await UpdateLocation()) { // Setup loader from updated location wLoader = new WeatherDataLoader(this.location, this, this); await RefreshWeather(false); } }; } dataReceiver = new LocalBroadcastReceiver(); dataReceiver.BroadcastReceived += async(context, intent) => { if (WearableHelper.LocationPath.Equals(intent?.Action) || WearableHelper.WeatherPath.Equals(intent?.Action)) { if (WearableHelper.WeatherPath.Equals(intent.Action) || (!loaded && location != null)) { if (timer.Enabled) { timer.Stop(); } // We got all our data; now load the weather wLoader = new WeatherDataLoader(location, this, this); await wLoader.ForceLoadSavedWeatherData(); } if (WearableHelper.LocationPath.Equals(intent.Action)) { // We got the location data location = Settings.HomeData; loaded = false; } } else if (WearableHelper.ErrorPath.Equals(intent?.Action)) { // An error occurred; cancel the sync operation await CancelDataSync(); } else if (WearableHelper.IsSetupPath.Equals(intent?.Action)) { if (Settings.DataSync != WearableDataSync.Off) { bool isDeviceSetup = intent.GetBooleanExtra(WearableDataListenerService.EXTRA_DEVICESETUPSTATUS, false); var connStatus = (WearConnectionStatus)intent.GetIntExtra(WearableDataListenerService.EXTRA_CONNECTIONSTATUS, 0); if (isDeviceSetup && connStatus == WearConnectionStatus.Connected) { // Device is setup and connected; proceed with sync Activity?.StartService(new Intent(Activity, typeof(WearableDataListenerService)) .SetAction(WearableDataListenerService.ACTION_REQUESTLOCATIONUPDATE)); Activity?.StartService(new Intent(Activity, typeof(WearableDataListenerService)) .SetAction(WearableDataListenerService.ACTION_REQUESTWEATHERUPDATE)); ResetTimer(); } else { // Device is not connected; cancel sync await CancelDataSync(); } } } }; loaded = true; }
private async Task Resume() { /* Update view on resume * ex. If temperature unit changed */ LocationData homeData = Settings.HomeData; // Did home change? bool homeChanged = false; if (location != null && FragmentManager.BackStackEntryCount == 0) { if (!location.Equals(homeData) && Tag == "home") { location = homeData; wLoader = null; homeChanged = true; } } // New Page = loaded - true // Navigating back to frag = !loaded - false if (loaded || homeChanged || wLoader == null) { await Restore(); loaded = true; } else if (wLoader != null && !loaded) { var culture = System.Globalization.CultureInfo.CurrentCulture; var locale = wm.LocaleToLangCode(culture.TwoLetterISOLanguageName, culture.Name); // Reset if source || locale is different if (weatherView.WeatherSource != Settings.API || wm.SupportsWeatherLocale && weatherView.WeatherLocale != locale) { await Restore(); loaded = true; } else if (wLoader.GetWeather()?.IsValid() == true) { Weather weather = wLoader.GetWeather(); // Update weather if needed on resume if (Settings.FollowGPS && await UpdateLocation()) { // Setup loader from updated location wLoader = new WeatherDataLoader(this.location, this, this); await RefreshWeather(false); loaded = true; } else { // Check weather data expiration if (!int.TryParse(weather.ttl, out int ttl)) { ttl = Settings.DefaultInterval; } TimeSpan span = DateTimeOffset.Now - weather.update_time; if (span.TotalMinutes > ttl) { await RefreshWeather(false); } else { weatherView.UpdateView(wLoader.GetWeather()); SetView(weatherView); loaded = true; } } } } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); if (e.Parameter != null) { string arg = e.Parameter.ToString(); switch (arg) { case "view-alerts": GotoAlertsPage(); break; default: break; } } LocationData LocParameter = e.Parameter as LocationData; if (e.NavigationMode == NavigationMode.New) { // Reset loader if new page instance created location = null; wLoader = null; MainViewer.ChangeView(null, 0, null); // New page instance created, so restore if (LocParameter != null) { location = LocParameter; wLoader = new WeatherDataLoader(location, this, this); } await Restore(); } else { LocationData homeData = Settings.HomeData; // Did home change? bool homeChanged = false; if (location != null && Frame.BackStack.Count == 0) { if (!location.Equals(homeData)) { location = homeData; homeChanged = true; } } if (wLoader != null) { var userlang = GlobalizationPreferences.Languages.First(); var culture = new CultureInfo(userlang); var locale = wm.LocaleToLangCode(culture.TwoLetterISOLanguageName, culture.Name); // Reset loader if source, query or locale is different bool resetLoader = WeatherView.WeatherSource != Settings.API || homeChanged; if (wm.SupportsWeatherLocale && !resetLoader) { resetLoader = WeatherView.WeatherLocale != locale; } if (resetLoader) { wLoader = null; } } // Update view on resume // ex. If temperature unit changed if ((wLoader != null) && !homeChanged) { await Resume(); if (location.query == homeData.query) { // Clear backstack since we're home Frame.BackStack.Clear(); SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed; } } else { await Restore(); } } }