protected override void onCreate(global::android.os.Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);
            var ll = new LinearLayout(this);
            ll.setOrientation(LinearLayout.VERTICAL);

            textLatitude = new TextView(this).AttachTo(ll);
            textLongitude = new TextView(this).AttachTo(ll);

            textLatitude.setText("?");
 
            setContentView(ll);

            locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
            Location lastLocation = locationManager.getLastKnownLocation(PROVIDER);
            if (lastLocation != null)
            {
                updateLoc(lastLocation);
            }

            this.myLocationListener = new MyLocationListener
            {
                __this = this
            };

            this.ShowToast("http://jsc-solutions.net");
        }
Ejemplo n.º 2
0
        protected override void onCreate(global::android.os.Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);
            var ll = new LinearLayout(this);

            ll.setOrientation(LinearLayout.VERTICAL);

            textLatitude  = new TextView(this).AttachTo(ll);
            textLongitude = new TextView(this).AttachTo(ll);

            textLatitude.setText("?");

            setContentView(ll);

            locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
            Location lastLocation = locationManager.getLastKnownLocation(PROVIDER);

            if (lastLocation != null)
            {
                updateLoc(lastLocation);
            }

            this.myLocationListener = new MyLocationListener
            {
                __this = this
            };

            this.ShowToast("http://jsc-solutions.net");
        }
        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            var xamApp          = new App();
            var permissions     = new iOSRequestPermissions();
            var errorHandler    = new ExceptionHandlerService();
            var locationManager = LocationListener.CreateLocationManager();

            locationManager.AllowsBackgroundLocationUpdates = true;
            if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            {
                locationManager.ShowsBackgroundLocationIndicator = true;
            }

            var locationService =
                LocationListener
                .CreatePlatform(exceptionHandler: errorHandler, locationManager: locationManager);


            errorHandler
            .OnError
            .Select(x => x as LocationActivationException)
            .Where(x => x?.Reason == ActivationFailedReasons.PermissionsIssue)
            .SelectMany(_ => permissions.Location)
            .Subscribe();

            xamApp
            .MainViewModel
            .SetLocationService(locationService);

            LoadApplication(xamApp);

            return(base.FinishedLaunching(app, options));
        }
Ejemplo n.º 4
0
 public void StartListening(long minTimeBetweenUpdates)
 {
     _locationManager  = (LocationManager)Forms.Context.GetSystemService(Context.LocationService);
     _locationListener = new LocationListener(LocationChanged);
     _locationManager.RequestLocationUpdates(LocationManager.GpsProvider, minTimeBetweenUpdates, 0, _locationListener);
     _locationManager.RequestLocationUpdates(LocationManager.NetworkProvider, minTimeBetweenUpdates, 0, _locationListener);
 }
Ejemplo n.º 5
0
        private void InitLocation()
        {
            LocationManager locationManager = (LocationManager)GetSystemService(LocationService);

            Criteria criteria  = new Criteria();
            string   mprovider = locationManager.GetBestProvider(criteria, false);

            location = locationManager.GetLastKnownLocation(mprovider);

            locationListener = new LocationListener();
            locationManager.RequestLocationUpdates(LocationManager.GpsProvider, 5000, 10, locationListener);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Stop monitoring.
        /// </summary>
        static partial void StopMonitoring()
        {
            var locationManager = (LocationManager)Application.Context.GetSystemService(Context.LocationService);

            if (locationManager != null)
            {
                locationManager.RemoveUpdates(listener);
            }

            listener.Dispose();
            listener = null;
        }
Ejemplo n.º 7
0
        //public ComputeRunEntryPoint(LocationManager locationManager)
        //{
        //    _locationManager = locationManager;
        //}

        public void Start()
        {
            _locationlistener = new LocationListener();
            _locationlistener.LocationChanged += OnLocationChanged;

            //LocationManager locationManager = (LocationManager) GetSystemService("location");
            Criteria locationCriteria = new Criteria();

            locationCriteria.Accuracy = Accuracy.Fine;

            string locationProvider = _locationManager.GetBestProvider(locationCriteria, true);

            _locationManager.RequestLocationUpdates(locationProvider, 0, 0, _locationlistener);
        }
        private void InitializeLocationManager(Action<Android.Locations.Location> callback)
        {
            if (_locationManager == null)
                _locationManager = (LocationManager)Application.Context.GetSystemService(Context.LocationService);

            // creatae a listener
            _listener = new LocationListener()
            {
                LocationChangedCallback = callback
            };

            // ask the location manager to start listening
            _locationManager.RequestLocationUpdates(LocationManager.GpsProvider, 0, 0, _listener);
            _locationManager.RequestLocationUpdates(LocationManager.NetworkProvider, 0, 0, _listener);
        }
Ejemplo n.º 9
0
        private void InitializeLocationManager(Action <Android.Locations.Location> callback)
        {
            if (_locationManager == null)
            {
                _locationManager = (LocationManager)Application.Context.GetSystemService(Context.LocationService);
            }

            // creatae a listener
            _listener = new LocationListener()
            {
                LocationChangedCallback = callback
            };

            // ask the location manager to start listening
            _locationManager.RequestLocationUpdates(LocationManager.GpsProvider, 0, 0, _listener);
            _locationManager.RequestLocationUpdates(LocationManager.NetworkProvider, 0, 0, _listener);
        }
        public void SetLocationService(ILocationListener service = null)
        {
            _locationServiceCrossPlatformSimple =
                service ??
                LocationListener.Create();


            _locationServiceCrossPlatformSimple
            .OnError
            .Subscribe(exc =>
            {
                Error = exc.ToString();
            });

            _locationServiceCrossPlatformSimple
            .IsListeningForChanges
            .Subscribe(isListening => IsListeningForLocationChanges = isListening);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Start monitoring.
        /// </summary>
        static partial void StartMonitoring()
        {
            listener = new LocationListener();

            var locationManager = (LocationManager)Application.Context.GetSystemService(Context.LocationService);

            if (locationManager == null)
            {
                return;
            }

            var criteria = new Criteria
            {
                Accuracy = DesiredAccuracy == Accuracy.High ? Android.Locations.Accuracy.Fine : Android.Locations.Accuracy.Coarse
            };

            var provider = locationManager.GetBestProvider(criteria, true);

            locationManager.RequestLocationUpdates(provider, 0, (float)LocationChangeThreshold, listener);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Start monitoring.
        /// </summary>
        static partial void StartMonitoring()
        {
            listener = new LocationListener();

            var locationManager = (LocationManager)Application.Context.GetSystemService(Context.LocationService);

            if (locationManager == null)
            {
                return;
            }

            var criteria = new Criteria
            {
                Accuracy = DesiredAccuracy == Accuracy.High ? Android.Locations.Accuracy.Fine : Android.Locations.Accuracy.Coarse
            };

            var provider = locationManager.GetBestProvider(criteria, true);

            locationManager.RequestLocationUpdates(provider, 0, (float)LocationChangeThreshold, listener);
        }
Ejemplo n.º 13
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            mapObjectManager = new MapObjectManager();

            SetContentView(Resource.Layout.activity_main);

            Android.Support.V7.Widget.Toolbar toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);

            FloatingActionButton fab = FindViewById <FloatingActionButton>(Resource.Id.fab);

            fab.Click += FabOnClick;


            GoogleMapOptions mapOptions = new GoogleMapOptions()
                                          .InvokeMapType(GoogleMap.MapTypeNormal)
                                          .InvokeZoomControlsEnabled(true)
                                          .InvokeCompassEnabled(true);



            mapFragment = MapFragment.NewInstance(mapOptions);

            FragmentTransaction fragTx = FragmentManager.BeginTransaction().Add(Resource.Id.mapContainer, mapFragment);

            fragTx.Commit();
            mapFragment.GetMapAsync(this);

            LocationManager locationManager = (LocationManager)GetSystemService(Android.Content.Context.LocationService);

            Criteria criteria  = new Criteria();
            string   mprovider = locationManager.GetBestProvider(criteria, false);

            location = locationManager.GetLastKnownLocation(mprovider);

            LocationListener locationListener = new LocationListener(this);

            locationManager.RequestLocationUpdates(LocationManager.GpsProvider, 5000, 10, locationListener);
        }
Ejemplo n.º 14
0
        //public override void RequestLocation()
        //{
        //    Criteria criteria = new Criteria();
        //    using (LocationManager locationManager = (LocationManager)Application.Context.GetSystemService(Application.LocationService))
        //    {
        //        string providerName = locationManager.GetBestProvider(criteria, true);
        //        using (System.Threading.EventWaitHandle waitLocation = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset))
        //        {
        //            using (LocationListener locationListener = new LocationListener(l => { }))
        //                ;
        //        }
        //    }
        //}

        private void SubscribeToLocationChanged(EventHandler <ValueEventArgs <MapPoint> > handler)
        {
            //handler(this, new ValueEventArgs<MapPoint>(new MapPoint(59.9982349516688, 30.2508131012369)));
            //return;
            Criteria criteria = new Criteria();
            //using (LocationManager locationManager = (LocationManager)Application.Context.GetSystemService(Application.LocationService))
            LocationManager locationManager = (LocationManager)Application.Context.GetSystemService(Application.LocationService);
            {
                string           providerName     = locationManager.GetBestProvider(criteria, true);
                LocationListener locationListener = new LocationListener(location =>
                {
                    if (handler != null && location != null)
                    {
                        handler(this, new ValueEventArgs <MapPoint>(new MapPoint(location.Latitude, location.Longitude)));
                    }
                });
                _locationChangedSubscriptions.AddOrUpdate(handler, locationListener, (h, l) => locationListener);
                locationManager.RequestLocationUpdates(providerName, 100L, 1f, locationListener);
                locationManager.RequestSingleUpdate(providerName, locationListener, null);
            }
        }
Ejemplo n.º 15
0
        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your fragment here
            Loaded = true;

            // Get ActionMode state
            if (savedInstanceState != null && savedInstanceState.GetBoolean("SearchUI", false))
            {
                inSearchUI = true;

                // Restart ActionMode
                mActionMode = AppCompatActivity.StartSupportActionMode(mActionModeCallback);
            }

            int max = Enum.GetValues(typeof(WeatherUtils.ErrorStatus)).Cast <int>().Max();

            ErrorCounter = new bool[max];

            mLocListnr = new LocationListener();
        }
Ejemplo n.º 16
0
        public override ActionResult <MapPoint> GetCurrentLocation()
        {
            Criteria criteria = new Criteria();

            using (LocationManager locationManager = (LocationManager)Application.Context.GetSystemService(Application.LocationService))
            {
                string providerName = locationManager.GetBestProvider(criteria, true);
                using (System.Threading.EventWaitHandle waitLocation = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset))
                {
                    using (LocationListener locationListener = new LocationListener(l => waitLocation.Set()))
                        locationManager.RequestSingleUpdate(providerName, locationListener, null);
                    waitLocation.WaitOne(3000);
                    Location location = string.IsNullOrWhiteSpace(providerName) ? null : locationManager.GetLastKnownLocation(providerName);
                    if (location == null)
                    {
                        return(ActionResult <MapPoint> .GetErrorResult(new NotSupportedException()));
                    }
                    using (location)
                        return(ActionResult <MapPoint> .GetValidResult(new MapPoint(location.Latitude, location.Longitude)));
                }
            }
        }
        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;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Stop monitoring.
        /// </summary>
        static partial void StopMonitoring()
        {
            var locationManager = (LocationManager)Application.Context.GetSystemService(Context.LocationService);

            if (locationManager != null)
            {
                locationManager.RemoveUpdates(listener);
            }

            listener.Dispose();
            listener = null;
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set the result to CANCELED.  This will cause the widget host to cancel
            // out of the widget placement if they press the back button.
            SetResult(Result.Canceled, new Intent().PutExtra(AppWidgetManager.ExtraAppwidgetId, mAppWidgetId));

            // Find the widget id from the intent.
            if (Intent != null && Intent.Extras != null)
            {
                mAppWidgetId = Intent.GetIntExtra(AppWidgetManager.ExtraAppwidgetId, AppWidgetManager.InvalidAppwidgetId);
            }

            if (mAppWidgetId == AppWidgetManager.InvalidAppwidgetId)
            {
                // If they gave us an intent without the widget id, just bail.
                Finish();
            }

            SetContentView(Resource.Layout.activity_widget_setup);

            wm = WeatherManager.GetInstance();

            // Setup location spinner
            locSpinner = FindViewById <Spinner>(Resource.Id.location_pref_spinner);
            locSummary = FindViewById <TextView>(Resource.Id.location_pref_summary);

            var comboList = new List <ComboBoxItem>()
            {
                new ComboBoxItem(GetString(Resource.String.pref_item_gpslocation), "GPS"),
                new ComboBoxItem(GetString(Resource.String.label_btn_add_location), "Search")
            };
            var favs = Task.Run(Settings.GetFavorites).Result;

            Favorites = new ReadOnlyCollection <LocationData>(favs);
            foreach (LocationData location in Favorites)
            {
                comboList.Insert(comboList.Count - 1, new ComboBoxItem(location.name, location.query));
            }

            locAdapter = new ArrayAdapter <ComboBoxItem>(
                this, Android.Resource.Layout.SimpleSpinnerItem,
                comboList);
            locAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            locAdapter.SetNotifyOnChange(true);
            locSpinner.Adapter = locAdapter;

            FindViewById(Resource.Id.location_pref).Click += (object sender, EventArgs e) =>
            {
                locSpinner.PerformClick();
            };
            locSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) =>
            {
                CtsCancel();

                if (locSpinner.SelectedItem is ComboBoxItem item)
                {
                    locSummary.Text = item.Display;

                    if (item.Value.Equals("Search"))
                    {
                        mActionMode = StartSupportActionMode(mActionModeCallback);
                    }
                    else
                    {
                        selectedItem = item;
                    }
                }
                else
                {
                    selectedItem = null;
                }
                query_vm = null;
            };
            locSpinner.SetSelection(0);

            // Setup interval spinner
            refreshSpinner     = FindViewById <Spinner>(Resource.Id.interval_pref_spinner);
            var refreshSummary = FindViewById <TextView>(Resource.Id.interval_pref_summary);
            var refreshList    = new List <ComboBoxItem>();
            var refreshEntries = this.Resources.GetStringArray(Resource.Array.refreshinterval_entries);
            var refreshValues  = this.Resources.GetStringArray(Resource.Array.refreshinterval_values);

            for (int i = 0; i < refreshEntries.Length; i++)
            {
                refreshList.Add(new ComboBoxItem(refreshEntries[i], refreshValues[i]));
            }
            var refreshAdapter = new ArrayAdapter <ComboBoxItem>(
                this, Android.Resource.Layout.SimpleSpinnerItem,
                refreshList);

            refreshAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            refreshSpinner.Adapter = refreshAdapter;
            FindViewById(Resource.Id.interval_pref).Click += (object sender, EventArgs e) =>
            {
                refreshSpinner.PerformClick();
            };
            refreshSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) =>
            {
                if (refreshSpinner.SelectedItem is ComboBoxItem item)
                {
                    refreshSummary.Text = item.Display;
                }
            };
            refreshSpinner.SetSelection(
                refreshList.FindIndex(item => item.Value.Equals(Settings.RefreshInterval.ToString())));

            SetSupportActionBar(FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar));
            SupportActionBar.SetDisplayHomeAsUpEnabled(true);
            SupportActionBar.SetHomeAsUpIndicator(Resource.Drawable.ic_arrow_back_white_24dp);

            mActionModeCallback.CreateActionMode  += OnCreateActionMode;
            mActionModeCallback.DestroyActionMode += OnDestroyActionMode;

            FindViewById(Resource.Id.search_fragment_container).Click += delegate
            {
                ExitSearchUi();
            };

            appBarLayout      = FindViewById <AppBarLayout>(Resource.Id.app_bar);
            collapsingToolbar = FindViewById <CollapsingToolbarLayout>(Resource.Id.collapsing_toolbar);

            cts = new CancellationTokenSource();

            // Location Listener
            mLocListnr = new LocationListener();
            mLocListnr.LocationChanged += async(Android.Locations.Location location) =>
            {
                mLocation = location;
                await FetchGeoLocation();
            };

            if (!Settings.WeatherLoaded)
            {
                Toast.MakeText(this, GetString(Resource.String.prompt_setup_app_first), ToastLength.Short).Show();

                Intent intent = new Intent(this, typeof(SetupActivity))
                                .SetAction(AppWidgetManager.ActionAppwidgetConfigure)
                                .PutExtra(AppWidgetManager.ExtraAppwidgetId, mAppWidgetId);
                StartActivityForResult(intent, SETUP_REQUEST_CODE);
            }
        }
Ejemplo n.º 20
0
        public override void OnCreate()
        {
            base.OnCreate();
            Log.Info(_tag, "OnCreate: the service is initializing.");

            _handler   = new Handler();
            _startTime = DateTime.UtcNow;

            _token = new UserToken
            {
                Token = (string)App.User.UserToken.Token.Clone()
            };
            _isGuard = App.User.IsGuard;

            Criteria criteria = new Criteria
            {
                Accuracy         = Accuracy.Fine,
                AltitudeRequired = false,
                BearingRequired  = false
            };

            _locationManager = Application.Context.GetSystemService(Context.LocationService) as LocationManager;

            if (_locationManager != null)
            {
                _locationProvider = _locationManager.GetBestProvider(criteria, true);
            }

            _locationListener = new LocationListener();

            if (_locationProvider != null)
            {
                Log.Verbose(_tag, "Location provider: " + _locationProvider);
            }
            else
            {
                Log.Error(_tag, "Location provider is null. Location events will not work.");
            }

            // This Action is only for demonstration purposes.
            _runnable = () =>
            {
                var duration = DateTime.UtcNow.Subtract(_startTime);
                var msg      = _wasReset ? $"Service restarted at {_startTime} ({duration:c} ago)."
                                                          : $"Service started at {_startTime} ({duration:c} ago).";

                try
                {
                    Update();
                }
                catch (WebException e)
                {
                    Log.Error(_tag, e.Message);
                }
                catch (Exception e)
                {
                    Log.Error(_tag, e.Message);
                }

                Log.Debug(_tag, msg);
                var i = new Intent(Constants.NotificationBroadcastAction);
                i.PutExtra(Constants.BroadcastMessageKey, msg);

                LocalBroadcastManager.GetInstance(this)
                .SendBroadcast(i);

                _handler.PostDelayed(_runnable, Constants.DelayBetweenLogMessages);
            };
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Check if this activity was started from adding a new widget
            if (Intent != null && AppWidgetManager.ActionAppwidgetConfigure.Equals(Intent.Action))
            {
                mAppWidgetId = Intent.GetIntExtra(AppWidgetManager.ExtraAppwidgetId, AppWidgetManager.InvalidAppwidgetId);

                if (Settings.WeatherLoaded || mAppWidgetId == AppWidgetManager.InvalidAppwidgetId)
                {
                    // This shouldn't happen, but just in case
                    SetResult(Android.App.Result.Ok);
                    Finish();
                    // Return if we're finished
                    return;
                }

                if (mAppWidgetId != AppWidgetManager.InvalidAppwidgetId)
                {
                    // Set the result to CANCELED.  This will cause the widget host to cancel
                    // out of the widget placement if they press the back button.
                    SetResult(Android.App.Result.Canceled, new Intent().PutExtra(AppWidgetManager.ExtraAppwidgetId, mAppWidgetId));
                }
            }

            SetContentView(Resource.Layout.activity_setup);

            mActionModeCallback.CreateActionMode  += OnCreateActionMode;
            mActionModeCallback.DestroyActionMode += OnDestroyActionMode;

            // Get ActionMode state
            if (savedInstanceState != null && savedInstanceState.GetBoolean("SearchUI", false))
            {
                inSearchUI = true;

                // Restart ActionMode
                mActionMode = StartSupportActionMode(mActionModeCallback);
            }

            wm = WeatherData.WeatherManager.GetInstance();

            searchViewContainer    = FindViewById(Resource.Id.search_bar);
            gpsFollowButton        = FindViewById <Button>(Resource.Id.gps_follow);
            progressBar            = FindViewById <ProgressBar>(Resource.Id.progressBar);
            progressBar.Visibility = ViewStates.Gone;

            // NOTE: Bug: Explicitly set tintmode on Lollipop devices
            if (Build.VERSION.SdkInt == BuildVersionCodes.Lollipop)
            {
                progressBar.IndeterminateTintMode = PorterDuff.Mode.SrcIn;
            }

            /* Event Listeners */
            searchViewContainer.Click += delegate
            {
                mActionMode = StartSupportActionMode(mActionModeCallback);
            };

            FindViewById(Resource.Id.search_fragment_container).Click += delegate
            {
                ExitSearchUi();
            };

            gpsFollowButton.Click += async delegate
            {
                await FetchGeoLocation();
            };

            // Location Listener
            mLocListnr = new LocationListener();
            mLocListnr.LocationChanged += async(Location location) =>
            {
                mLocation = location;
                await FetchGeoLocation();
            };

            // Reset focus
            FindViewById(Resource.Id.activity_setup).RequestFocus();

            // Set default API to HERE
            Settings.API = WeatherData.WeatherAPI.Here;
            wm.UpdateAPI();

            if (String.IsNullOrWhiteSpace(wm.GetAPIKey()))
            {
                // If (internal) key doesn't exist, fallback to Yahoo
                Settings.API = WeatherData.WeatherAPI.Yahoo;
                wm.UpdateAPI();
                Settings.UsePersonalKey = true;
                Settings.KeyVerified    = false;
            }
            else
            {
                // If key exists, go ahead
                Settings.UsePersonalKey = false;
                Settings.KeyVerified    = true;
            }
        }