Esempio n. 1
0
        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
                }
            }
        }
Esempio n. 2
0
        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();
            }
        }
Esempio n. 3
0
        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
            }
        }
Esempio n. 4
0
        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);
                }
            }
        }
Esempio n. 5
0
        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;
        }
Esempio n. 6
0
 private void MoveData(LocationPanelViewModel view, int fromIdx, int toIdx)
 {
     // Only move panels if we haven't already
     if (LocationPanels.IndexOf(view) != toIdx)
     {
         LocationPanels.Move(fromIdx, toIdx);
     }
 }
Esempio n. 7
0
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
        {
            switch (requestCode)
            {
            case PERMISSION_LOCATION_REQUEST_CODE:
            {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.Length > 0 &&
                    grantResults[0] == Permission.Granted)
                {
                    // permission was granted, yay!
                    // Do the task you need to do.
                    Task.Run(async() =>
                        {
                            var locData = await UpdateLocation();
                            if (locData != null)
                            {
                                Settings.SaveLastGPSLocData(locData);
                                await LoadGPSPanel();

                                App.Context.StartService(
                                    new Intent(App.Context, typeof(WearableDataListenerService))
                                    .SetAction(WearableDataListenerService.ACTION_SENDLOCATIONUPDATE));
                            }
                            else
                            {
                                AppCompatActivity?.RunOnUiThread(() =>
                                {
                                    gpsPanelViewModel         = null;
                                    gpsPanelLayout.Visibility = ViewStates.Gone;
                                });
                            }
                        });
                }
                else
                {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Settings.FollowGPS        = false;
                    gpsPanelViewModel         = null;
                    gpsPanelLayout.Visibility = ViewStates.Gone;
                    Toast.MakeText(AppCompatActivity, Resource.String.error_location_denied, ToastLength.Short).Show();
                }
                return;
            }

            default:
                break;
            }
        }
        // Replace the contents of a view (invoked by the layout manager)
        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            // - get element from your dataset at this position
            // - replace the contents of the view with that element
            ViewHolder             vh        = holder as ViewHolder;
            Context                context   = vh.mLocView.Context;
            LocationPanelViewModel panelView = mDataset[position];

            // Background
            Glide.AsBitmap()
            .Load(panelView.Background)
            .Apply(new RequestOptions()
                   .CenterCrop()
                   .Error(vh.mLocView.colorDrawable)
                   .Placeholder(vh.mLocView.colorDrawable))
            .Into(new GlideBitmapViewTarget(vh.mBgImageView, () => vh.mLocView.SetWeather(panelView)));
        }
Esempio n. 9
0
        private async Task Resume()
        {
            // Update view on resume
            // ex. If temperature unit changed
            AppCompatActivity?.RunOnUiThread(() =>
            {
                var colorDrawable = new ColorDrawable(
                    new Color(ContextCompat.GetColor(AppCompatActivity, Resource.Color.colorPrimary)));
                AppCompatActivity?.SupportActionBar.SetBackgroundDrawable(colorDrawable);

                if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
                {
                    AppCompatActivity?.Window.SetStatusBarColor(
                        new Color(ContextCompat.GetColor(AppCompatActivity, Resource.Color.colorPrimaryDark)));
                }

                if (Settings.FollowGPS)
                {
                    gpsPanelLayout.Visibility = ViewStates.Visible;
                }
                else
                {
                    gpsPanelViewModel         = null;
                    gpsPanelLayout.Visibility = ViewStates.Gone;
                }
            });

            if (mAdapter.ItemCount == 0 || Settings.FollowGPS && gpsPanelViewModel == null)
            {
                // New instance; Get locations and load up weather data
                await LoadLocations();
            }
            else if (!Loaded)
            {
                // Refresh view
                await RefreshLocations();

                Loaded = true;
            }
        }
Esempio n. 10
0
        private void AddSearchFragment()
        {
            if (mSearchFragment != null)
            {
                return;
            }

            FragmentTransaction    ft             = ChildFragmentManager.BeginTransaction();
            LocationSearchFragment searchFragment = new LocationSearchFragment();

            searchFragment.SetClickListener(async(object sender, RecyclerClickEventArgs e) =>
            {
                if (mSearchFragment == null)
                {
                    return;
                }

                LocationQueryAdapter adapter = sender as LocationQueryAdapter;
                LocationQuery v = (LocationQuery)e.View;
                LocationQueryViewModel query_vm = null;

                try
                {
                    if (!String.IsNullOrEmpty(adapter.Dataset[e.Position].LocationQuery))
                    {
                        query_vm = adapter.Dataset[e.Position];
                    }
                }
                catch (Exception)
                {
                    query_vm = null;
                }
                finally
                {
                    if (query_vm == null)
                    {
                        query_vm = new LocationQueryViewModel();
                    }
                }

                if (String.IsNullOrWhiteSpace(query_vm.LocationQuery))
                {
                    // Stop since there is no valid query
                    return;
                }

                // Cancel other tasks
                mSearchFragment.CtsCancel();
                var ctsToken = mSearchFragment.GetCancellationTokenSource().Token;

                ShowLoading(true);

                if (ctsToken.IsCancellationRequested)
                {
                    ShowLoading(false);
                    return;
                }

                // Check if location already exists
                var locData = await Settings.GetLocationData();
                if (locData.Exists(l => l.query == query_vm.LocationQuery))
                {
                    ShowLoading(false);
                    ExitSearchUi();
                    return;
                }

                if (ctsToken.IsCancellationRequested)
                {
                    ShowLoading(false);
                    return;
                }

                var location = new LocationData(query_vm);
                if (!location.IsValid())
                {
                    Toast.MakeText(App.Context, App.Context.GetString(Resource.String.werror_noweather), ToastLength.Short).Show();
                    ShowLoading(false);
                    return;
                }
                Weather weather = await Settings.GetWeatherData(location.query);
                if (weather == null)
                {
                    try
                    {
                        weather = await wm.GetWeather(location);
                    }
                    catch (WeatherException wEx)
                    {
                        weather = null;
                        Toast.MakeText(App.Context, wEx.Message, ToastLength.Short).Show();
                    }
                }

                if (weather == null)
                {
                    ShowLoading(false);
                    return;
                }

                // We got our data so disable controls just in case
                mAdapter.Dataset.Clear();
                mAdapter.NotifyDataSetChanged();

                if (mSearchFragment?.View != null &&
                    mSearchFragment?.View?.FindViewById(Resource.Id.recycler_view) is RecyclerView recyclerView)
                {
                    recyclerView.Enabled = false;
                }

                // Save data
                await Settings.AddLocation(location);
                if (wm.SupportsAlerts && weather.weather_alerts != null)
                {
                    await Settings.SaveWeatherAlerts(location, weather.weather_alerts);
                }
                await Settings.SaveWeatherData(weather);

                var panel = new LocationPanelViewModel(weather)
                {
                    LocationData = location
                };

                // Set properties if necessary
                if (EditMode)
                {
                    panel.EditMode = true;
                }

                int index = mAdapter.Dataset.Count;
                mAdapter.Add(panel);

                // Update shortcuts
                Task.Run(Shortcuts.ShortcutCreator.UpdateShortcuts);

                // Hide dialog
                ShowLoading(false);
                ExitSearchUi();
            });
            searchFragment.UserVisibleHint = false;
            ft.Add(Resource.Id.search_fragment_container, searchFragment);
            ft.CommitAllowingStateLoss();
        }
Esempio n. 11
0
        private async Task <LocationData> UpdateLocation()
        {
            LocationData locationData = null;

            if (Settings.FollowGPS)
            {
                if (AppCompatActivity != null && ContextCompat.CheckSelfPermission(AppCompatActivity, Manifest.Permission.AccessFineLocation) != Permission.Granted &&
                    ContextCompat.CheckSelfPermission(AppCompatActivity, Manifest.Permission.AccessCoarseLocation) != Permission.Granted)
                {
                    ActivityCompat.RequestPermissions(AppCompatActivity, new String[] { Manifest.Permission.AccessCoarseLocation, Manifest.Permission.AccessFineLocation },
                                                      PERMISSION_LOCATION_REQUEST_CODE);
                    return(null);
                }

                LocationManager locMan       = (LocationManager)AppCompatActivity.GetSystemService(Context.LocationService);
                bool            isGPSEnabled = locMan.IsProviderEnabled(LocationManager.GpsProvider);
                bool            isNetEnabled = locMan.IsProviderEnabled(LocationManager.NetworkProvider);

                Android.Locations.Location location = null;

                if (isGPSEnabled || isNetEnabled)
                {
                    Criteria locCriteria = new Criteria()
                    {
                        Accuracy = Accuracy.Coarse, CostAllowed = false, PowerRequirement = Power.Low
                    };
                    string provider = locMan.GetBestProvider(locCriteria, true);
                    location = locMan.GetLastKnownLocation(provider);

                    if (location == null)
                    {
                        locMan.RequestSingleUpdate(provider, mLocListnr, null);
                    }
                    else
                    {
                        LocationQueryViewModel view = null;

                        await Task.Run(async() =>
                        {
                            view = await wm.GetLocation(location);

                            if (String.IsNullOrEmpty(view.LocationQuery))
                            {
                                view = new LocationQueryViewModel();
                            }
                        });

                        if (String.IsNullOrWhiteSpace(view.LocationQuery))
                        {
                            // Stop since there is no valid query
                            AppCompatActivity?.RunOnUiThread(() =>
                            {
                                gpsPanelViewModel         = null;
                                gpsPanelLayout.Visibility = ViewStates.Gone;
                            });
                            return(null);
                        }

                        // Save location as last known
                        locationData = new LocationData(view, location);
                    }
                }
                else
                {
                    AppCompatActivity?.RunOnUiThread(() =>
                    {
                        Toast.MakeText(AppCompatActivity, Resource.String.error_retrieve_location, ToastLength.Short).Show();
                        gpsPanelViewModel         = null;
                        gpsPanelLayout.Visibility = ViewStates.Gone;
                    });
                }
            }

            return(locationData);
        }
 public void Add(LocationPanelViewModel item)
 {
     mDataset.Add(item);
     NotifyItemInserted(mDataset.IndexOf(item));
 }
Esempio n. 13
0
        private async void Location_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
        {
            LocationQueryViewModel query_vm = null;

            if (args.ChosenSuggestion != null)
            {
                // User selected an item from the suggestion list, take an action on it here.
                var theChosenOne = args.ChosenSuggestion as LocationQueryViewModel;

                if (!String.IsNullOrEmpty(theChosenOne.LocationQuery))
                {
                    query_vm = theChosenOne;
                }
                else
                {
                    query_vm = new LocationQueryViewModel();
                }
            }
            else if (!String.IsNullOrEmpty(args.QueryText))
            {
                // Use args.QueryText to determine what to do.
                var result = (await wm.GetLocations(args.QueryText)).First();

                if (result != null && !String.IsNullOrWhiteSpace(result.LocationQuery))
                {
                    sender.Text = result.LocationName;
                    query_vm    = result;
                }
                else
                {
                    query_vm = new LocationQueryViewModel();
                }
            }
            else if (String.IsNullOrWhiteSpace(args.QueryText))
            {
                // Stop since there is no valid query
                return;
            }

            if (String.IsNullOrWhiteSpace(query_vm.LocationQuery))
            {
                // Stop since there is no valid query
                return;
            }

            // Cancel other tasks
            cts.Cancel();
            cts = new CancellationTokenSource();
            var ctsToken = cts.Token;

            LoadingRing.IsActive = true;

            if (ctsToken.IsCancellationRequested)
            {
                LoadingRing.IsActive = false;
                return;
            }

            // Check if location already exists
            var locData = await Settings.GetLocationData();

            if (locData.Exists(l => l.query == query_vm.LocationQuery))
            {
                LoadingRing.IsActive = false;
                ShowAddLocationsPanel(false);
                return;
            }

            if (ctsToken.IsCancellationRequested)
            {
                LoadingRing.IsActive = false;
                return;
            }

            var location = new LocationData(query_vm);

            if (!location.IsValid())
            {
                await Toast.ShowToastAsync(App.ResLoader.GetString("WError_NoWeather"), ToastDuration.Short);

                LoadingRing.IsActive = false;
                return;
            }
            var weather = await Settings.GetWeatherData(location.query);

            if (weather == null)
            {
                try
                {
                    weather = await wm.GetWeather(location);
                }
                catch (WeatherException wEx)
                {
                    weather = null;
                    await Toast.ShowToastAsync(wEx.Message, ToastDuration.Short);
                }
            }

            if (weather == null)
            {
                LoadingRing.IsActive = false;
                return;
            }

            // We got our data so disable controls just in case
            sender.IsSuggestionListOpen = false;

            // Save data
            await Settings.AddLocation(location);

            if (wm.SupportsAlerts && weather.weather_alerts != null)
            {
                await Settings.SaveWeatherAlerts(location, weather.weather_alerts);
            }
            await Settings.SaveWeatherData(weather);

            var panelView = new LocationPanelViewModel(weather)
            {
                LocationData = location
            };

            // Set properties if necessary
            if (EditMode)
            {
                panelView.EditMode = true;
            }

            // Add to collection
            LocationPanels.Add(panelView);

            // Hide add locations panel
            LoadingRing.IsActive = false;
            ShowAddLocationsPanel(false);
        }