コード例 #1
0
        private void InitializeGoogleAPI()
        {
            int queryResult = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(Android.App.Application.Context);

            if (queryResult == ConnectionResult.Success)
            {
                string message = string.Format("{0} - {1}", CrossGeofence.Id, "Google Play services is available.");
                System.Diagnostics.Debug.WriteLine(message);

                if (mGeofenceClient == null)
                {
                    mGeofenceClient = LocationServices.GetGeofencingClient(Android.App.Application.Context);
                }

                if (mFusedLocationClient == null)
                {
                    var locationRequest = GetLocationRequest();
                    mFusedLocationClient = LocationServices.GetFusedLocationProviderClient(Android.App.Application.Context);
                    mFusedLocationClient.RequestLocationUpdatesAsync(locationRequest, new FusedLocationCallback(this));
                }

                //if (!mGoogleApiClient.IsConnected)
                //{
                //    mGoogleApiClient.Connect();
                //}
            }
            else
            {
                string message = string.Format("{0} - {1}", CrossGeofence.Id, "Google Play services is unavailable.");
                System.Diagnostics.Debug.WriteLine(message);
                CrossGeofence.GeofenceListener.OnError(message);
            }
        }
コード例 #2
0
        public async void OnMapReady(GoogleMap googleMap)
        {
            async Task GetLastLocationFromDevice()
            {
                FusedLocationProviderCallback fused = new FusedLocationProviderCallback(this);
                //Android.Locations.Location location = await fusedLocationProviderClient.RequestLocationUpdatesAsync(locationRequest, fused);
                //await fusedLocationProviderClient.RequestLocationUpdatesAsync(locationRequest, fused);
                await fusedLocationProviderClient.RequestLocationUpdatesAsync(locationRequest, fused);

                // Do something with the location
                //Log.Debug("SampleInMain", "The latitude is " + location.Latitude);
                //MarkerOptions markerOptions = new MarkerOptions();
                //markerOptions.SetPosition(fused.ReturnCurrentPosition());
                //markerOptions.SetTitle("Current Position");
                //googleMap.AddMarker(markerOptions);


                //if (location == null)
                //{
                //    // Seldom happens, but should code that handles this scenario
                //}
                //else
                //{

                //}
            }

            await GetLastLocationFromDevice();
        }
コード例 #3
0
        protected void StartLocationUpdates()         //must run on UI thread
        {
            try
            {
                int interval;
                if (!(Session.InAppLocationRate is null))
                {
                    interval = (int)Session.InAppLocationRate;
                }
                else
                {
                    interval = (int)Settings.InAppLocationRate;
                }

                LocationRequest locationRequest = new LocationRequest()
                                                  .SetFastestInterval((long)(interval * 1000 * 0.8))
                                                  .SetInterval(interval * 1000);
                if (Session.LocationAccuracy == 0)
                {
                    locationRequest.SetPriority(LocationRequest.PriorityBalancedPowerAccuracy);
                }
                else
                {
                    locationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
                }
                locationCallback = new FusedLocationProviderCallback(this);
                fusedLocationProviderClient.RequestLocationUpdatesAsync(locationRequest, locationCallback);
                locationUpdating    = true;
                currentLocationRate = interval;

                CommonMethods.LogStatic("Location updates started with interval " + interval);
            }
コード例 #4
0
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            UserDialogs.Init(this);

            FirebaseApp.InitializeApp(this);
            firebaseAnalytics = FirebaseAnalytics.GetInstance(this);

            var playAvailable = IsPlayServicesAvailable();

            if (playAvailable)
            {
                new GetRemoteConfig();
                Intent locIntent = new Intent(this, typeof(SaleLocationService));
                StartService(locIntent);
                fusedLocationProviderClient = LocationServices.GetFusedLocationProviderClient(this);
                FusedLocationProviderCallback callback = new FusedLocationProviderCallback(this);
                fusedLocationProviderClient.RequestLocationUpdatesAsync(callback.LocationRequest, callback);
            }

            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);
            global::Xamarin.FormsMaps.Init(this, bundle);
            LoadApplication(new App());
#if DEBUG
            MocksLocation();
#endif
        }
コード例 #5
0
ファイル: TrainingActivity.cs プロジェクト: jakubiakm/Gomando
        async Task StartLocationUpdatesAsync()
        {
            // Create a callback that will get the location updates
            if (locationCallback == null)
            {
                locationCallback = new MyLocationCallback();
                locationCallback.LocationUpdated += OnLocationResult;
            }

            // Get the current client
            if (locationClient == null)
            {
                locationClient = LocationServices.GetFusedLocationProviderClient(this);
            }

            try
            {
                //Create request and set intervals:
                //Interval: Desired interval for active location updates, it is inexact and you may not receive upates at all if no location servers are available
                //Fastest: Interval is exact and app will never receive updates faster than this value
                var locationRequest = new LocationRequest()
                                      .SetInterval(10000)
                                      .SetFastestInterval(5000)
                                      .SetPriority(LocationRequest.PriorityHighAccuracy);

                await locationClient.RequestLocationUpdatesAsync(locationRequest, locationCallback);
            }
            catch (Exception)
            {
            }
        }
コード例 #6
0
        public async Task <Position> GetLocationAsync()
        {
            tcsResult = new TaskCompletionSource <bool>();
            Context context = Android.App.Application.Context;

            fusedLocationProviderClient = LocationServices.GetFusedLocationProviderClient(context);
            LocationRequest locationRequest = new LocationRequest();

            //Set the location update interval (int milliseconds).
            locationRequest.SetInterval(10000);
            //Set the weight.
            locationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);

            try
            {
                await fusedLocationProviderClient.RequestLocationUpdatesAsync(locationRequest, this, Looper.MainLooper);

                await tcsResult.Task;
                Log.Info(Tag, $"User Location {userLocation.Longitude},{userLocation.Latitude}");
                return(userLocation);
            }
            catch (Exception e)
            {
                Log.Error(Tag, $"GetLocationAsync exception: {e.Message}");
            }

            return(null);
        }
コード例 #7
0
        /*
         * Start receiving location updates
         */
        void ILocationManager.StartLocationUpdates()
        {
            client = LocationServices.GetFusedLocationProviderClient(CrossCurrentActivity.Current.Activity);
            LocationRequest request = new LocationRequest().SetPriority(LocationRequest.PriorityHighAccuracy).SetInterval(1000 * 5).SetFastestInterval(1000 * 2);

            locationCallback = new ClientLocationCallback(CrossCurrentActivity.Current.Activity);
            client.RequestLocationUpdatesAsync(request, locationCallback);
        }
コード例 #8
0
        public async Task GetLocationUpdates(Action <WeatherLocation> action, Action error)
        {
            var locationRequest = new LocationRequest()
                                  .SetPriority(LocationRequest.PriorityLowPower)
                                  .SetInterval(60 * 1000 * 5)
                                  .SetFastestInterval(60 * 1000 * 2);

            _locationCallback = new FusedLocationProviderCallback(action, error);
            await _locationProvider.RequestLocationUpdatesAsync(locationRequest, _locationCallback);
        }
        private async Task StartLocationUpdates()
        {
            var request = new LocationRequest()
                          .SetSmallestDisplacement(10)
                          .SetInterval(10000)
                          .SetPriority(LocationRequest.PriorityHighAccuracy);

            await _fusedLocationClient.RequestLocationUpdatesAsync(request, _locationCallback, null);

            Toast.MakeText(this, "Location Updates Began", ToastLength.Long).Show();
        }
コード例 #10
0
        private async Task RequestLocationUpdates()
        {
            if (ContextCompat.CheckSelfPermission(Application.Context, Manifest.Permission.AccessFineLocation) !=
                Permission.Granted)
            {
                return;
            }
            await _fusedLocationProviderClient.RequestLocationUpdatesAsync(_locationRequest, _locationCallback);

            _isRequestingLocationUpdates = true;
        }
コード例 #11
0
 async Task StartRequestingLocationUpdates()
 {
     try
     {
         await fusedLocationProviderClient.RequestLocationUpdatesAsync(locationRequest, locationCallback);
     }
     catch (Exception ex)
     {
         Log.Error("GPS EXCEPTION", ex.StackTrace);
     }
 }
コード例 #12
0
        private async Task CreateLocationRequest()
        {
            _mLocationRequest = new LocationRequest();
            _mLocationRequest.SetInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
            _mLocationRequest.SetFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
            _mLocationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
            LocationRequestCallback = new LocationCallback();
            LocationRequestCallback.LocationResult += OnLocationRequestResult;
            await FusedLocationProviderClient.RequestLocationUpdatesAsync(_mLocationRequest, LocationRequestCallback);

            _requestingLocationUpdates = true;
        }
コード例 #13
0
        public async Task StartUpdatingLocationAsync()
        {
            if (IsGooglePlayServicesInstalled())
            {
                LocationRequest locationRequest = new LocationRequest()
                                                  .SetPriority(LocationRequest.PriorityHighAccuracy)
                                                  .SetInterval(1000 * 10)
                                                  .SetFastestInterval(1000 * 1);

                await _fusedLocationProviderClient.RequestLocationUpdatesAsync(locationRequest, this);
            }
        }
コード例 #14
0
ファイル: MainActivity.cs プロジェクト: xaaviair/blog-samples
        async Task StartLocationUpdatesAsync()
        {
            if (requestingUpdates)
            {
                return;
            }

            try
            {
                //Check our state here to ensure location is turned on
                await settingsClient.CheckLocationSettingsAsync(locationSettingsRequest);

                //Subscribe for location changes
                locationCallback.LocationUpdated += OnLocationResult;

                await fusedLocationClient.RequestLocationUpdatesAsync(locationRequest, locationCallback);

                //If success then we can update the UI
                requestingUpdates = true;
                UpdateUI();
            }
            catch (ApiException ex)
            {
                switch (ex.StatusCode)
                {
                case CommonStatusCodes.ResolutionRequired:
                    try
                    {
                        // Show the dialog by calling startResolutionForResult(), and check the
                        // result in onActivityResult().
                        var rae = (ResolvableApiException)ex;
                        rae.StartResolutionForResult(this, RequestCheckSettings);
                    }
                    catch (IntentSender.SendIntentException sie)
                    {
                        Debug.WriteLine("PendingIntent unable to execute request.");
                    }
                    break;

                case LocationSettingsStatusCodes.SettingsChangeUnavailable:
                    var message = "Location settings are inadequate and cannot be changed, please fix in settings.";
                    Toast.MakeText(this, message, ToastLength.Long).Show();
                    break;
                }
            }
            catch (Exception ex2)
            {
                var message = $"Unknown error occured.";
                Toast.MakeText(this, message, ToastLength.Long).Show();
            }
        }
コード例 #15
0
        public async Task RequestLocationUpdatesAsync(MainActivity mainActivity)
        {
            if (!HasPermissions(mainActivity) || !HasGooglePlayServicesInstalled(mainActivity))
            {
                return;
            }

            LocationRequest locationRequest = new LocationRequest()
                                              .SetPriority(LocationRequest.PriorityHighAccuracy)
                                              .SetInterval(60 * 1000 * 5)
                                              .SetFastestInterval(60 * 1000 * 2);

            await fusedLocationProviderClient.RequestLocationUpdatesAsync(locationRequest, new FusedLocationProviderCallback(mainActivity));
        }
コード例 #16
0
        async Task SetupLocationProvider()
        {
            var LocRequest = new LocationRequest();

            LocRequest.SetInterval(1000);
            LocRequest.SetFastestInterval(10 * 1000);
            LocRequest.SetSmallestDisplacement(100);
            LocRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
            LocationProviderClient = LocationServices.GetFusedLocationProviderClient(this);
            var locationCallback = new LocationCallbacker();

            locationCallback.MyLocationHandler = LocationCallback_LocationResult;
            await LocationProviderClient.RequestLocationUpdatesAsync(LocRequest, locationCallback);
        }
コード例 #17
0
        internal void StartLocationUpdates()
        {
            Android.Gms.Location.LocationRequest mLocationRequest = new Android.Gms.Location.LocationRequest();
            mLocationRequest.SetInterval(CrossGeofence.LocationUpdatesInterval == 0 ? 30000 : CrossGeofence.LocationUpdatesInterval);
            mLocationRequest.SetFastestInterval(CrossGeofence.FastestLocationUpdatesInterval == 0 ? 5000 : CrossGeofence.FastestLocationUpdatesInterval);
            string priorityType = "Balanced Power";

            switch (CrossGeofence.GeofencePriority)
            {
            case GeofencePriority.HighAccuracy:
                priorityType = "High Accuracy";
                mLocationRequest.SetPriority(Android.Gms.Location.LocationRequest.PriorityHighAccuracy);
                break;

            case GeofencePriority.LowAccuracy:
                priorityType = "Low Accuracy";
                mLocationRequest.SetPriority(Android.Gms.Location.LocationRequest.PriorityLowPower);
                break;

            case GeofencePriority.LowestAccuracy:
                priorityType = "Lowest Accuracy";
                mLocationRequest.SetPriority(Android.Gms.Location.LocationRequest.PriorityNoPower);
                break;

            case GeofencePriority.MediumAccuracy:
            case GeofencePriority.AcceptableAccuracy:
            default:
                mLocationRequest.SetPriority(Android.Gms.Location.LocationRequest.PriorityBalancedPowerAccuracy);
                break;
            }

            System.Diagnostics.Debug.WriteLine(string.Format("{0} - {1}: {2}", CrossGeofence.Id, "Priority set to", priorityType));
            //(Regions.Count == 0) ? (CrossGeofence.SmallestDisplacement==0?50 :CrossGeofence.SmallestDisplacement): Regions.Min(s => (float)s.Value.Radius)
            if (CrossGeofence.SmallestDisplacement > 0)
            {
                mLocationRequest.SetSmallestDisplacement(CrossGeofence.SmallestDisplacement);
                System.Diagnostics.Debug.WriteLine(string.Format("{0} - {1}: {2} meters", CrossGeofence.Id, "Location smallest displacement set to", CrossGeofence.SmallestDisplacement));
            }

            try
            {
                mFusedLocationProviderClient.RequestLocationUpdatesAsync(this.mLocationRequest, GeofenceLocationListener.SharedInstance);
            }
            catch (System.Exception e)
            {
                // Do not crash the app if permissions are disabled on Android Marshmallow
                System.Diagnostics.Debug.WriteLine(e.Message);
                CrossGeofence.GeofenceListener.OnError(e.Message);
            }
        }
コード例 #18
0
        private async void ElTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            elTimer.Enabled = false;
            await DB.CreateTableAsync <DeviceLocation>();

            if (Context != null)
            {
                ((Activity)Context).RunOnUiThread(async() => { await fusedLocationProviderClient.RequestLocationUpdatesAsync(LocationRequest, LocationCallback); });
            }
            else
            {
                var callbackIntent = PendingIntentFactory.
                                     fusedLocationProviderClient.RequestLocationUpdatesAsync(locationRequest);
            }
        }
コード例 #19
0
 public async System.Threading.Tasks.Task RequestLocationUpdatesAsync()
 {
     Log.Debug(Tag, "Requesting location updates");
     Utils.SetRequestingLocationUpdates(this, true);
     StartService(new Intent(ApplicationContext, typeof(LocationUpdatesService)));
     try
     {
         await FusedLocationClient.RequestLocationUpdatesAsync(LocationRequest, LocationCallback, Looper.MyLooper());
     }
     catch (SecurityException unlikely)
     {
         Utils.SetRequestingLocationUpdates(this, false);
         Log.Error(Tag, "Lost location permission. Could not request updates. " + unlikely);
     }
 }
コード例 #20
0
        public async Task StartAsync(MvxLocationOptions options)
        {
            EnsureGooglePlayServiceAvailable(_context);

            if (_client == null)
            {
                _client = LocationServices.GetFusedLocationProviderClient(_context);
            }

            // Create location request.
            _request = CreateLocationRequest(options);

            // Start receiving location updates.
            await _client.RequestLocationUpdatesAsync(_request, this, Looper.MainLooper);
        }
コード例 #21
0
        public async Task StartLocationRequestAsync(Activity activity)
        {
            FusedLocationProviderClient fusedLocationProvider = LocationServices.GetFusedLocationProviderClient(activity);

            await getLastLocationFromDevice(fusedLocationProvider);

            LocationRequest locationRequest = new LocationRequest()
                                              .SetPriority(LocationRequest.PriorityHighAccuracy)
                                              .SetInterval(10000)
                                              .SetFastestInterval(10000);

            await fusedLocationProvider.RequestLocationUpdatesAsync(locationRequest, ((MainActivity)activity).locationCallback);

            screenActivity = activity;
        }
コード例 #22
0
        public async Task StartLocationUpdates()
        {
            try
            {
                var locationRequest = new LocationRequest()
                                      .SetInterval(5000)
                                      .SetFastestInterval(5000)
                                      .SetPriority(LocationRequest.PriorityHighAccuracy);

                await locationProvider.RequestLocationUpdatesAsync(locationRequest, locationCallback);
            }
            catch (Exception e)
            {
                // TODO: log, tell user
            }
        }
コード例 #23
0
        void StartLocationUpdates()
        {
            try
            {
                // Create a callback that will get the location updates
                if (locationCallback == null)
                {
                    locationCallback = new MyLocationCallback();
                    locationCallback.LocationUpdated += OnLocationResult;
                }

                // Get the current client
                if (client == null)
                {
                    client = LocationServices.GetFusedLocationProviderClient(this);
                }

                //Create request and set intervals:
                //Interval: Desired interval for active location updates, it is inexact and you may not receive upates at all if no location servers are available
                //Fastest: Interval is exact and app will never receive updates faster than this value
                var locationRequest = new LocationRequest()
                                      .SetInterval(10000)
                                      .SetFastestInterval(5000)
                                      .SetPriority(LocationRequest.PriorityHighAccuracy);

                RunOnUiThread(async() =>
                {
                    try
                    {
                        await client.RequestLocationUpdatesAsync(locationRequest, locationCallback);
                    }
                    catch (Exception ex)
                    {
                        Utils.Eros = ex;
                        StartActivity(new Intent(Application.Context, typeof(ErosActivity)));
                    }
                });
            }
            catch (Exception ex)
            {
                RunOnUiThread(() =>
                {
                    Utils.Eros = ex;
                    StartActivity(new Intent(Application.Context, typeof(ErosActivity)));
                });
            }
        }
コード例 #24
0
        public void Start(LocationConfigBase config, Action <GeoLocation> locationChanged, Action <Exception> locationError)
        {
            _LocationChanged = locationChanged;
            _LocationError   = locationError;

            LocationRequest request = new LocationRequest().SetPriority((config.Accuracy == LocationAccuracy.Course) ? LocationRequest.PriorityLowPower : LocationRequest.PriorityHighAccuracy);

            if (config.MovementThreshold > 0)
            {
                request.SetSmallestDisplacement(config.MovementThreshold);
            }
            else
            {
                request.SetInterval(config.UpdateInterval).SetFastestInterval(config.UpdateInterval);
            }
            Task.Run(async() => await _Client.RequestLocationUpdatesAsync(request, this));
        }
コード例 #25
0
        private async Task GetLocationUpdates(FusedLocationProviderClient fusedLocationProviderClient, LocationCallback locationCallback)
        {
            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) == Android.Content.PM.Permission.Granted)
            {
                var locationRequest = new LocationRequest()
                                      .SetPriority(LocationRequest.PriorityHighAccuracy)
                                      .SetInterval(60 * 1000 * 5)
                                      .SetFastestInterval(60 * 500);

                await fusedLocationProviderClient.RequestLocationUpdatesAsync(locationRequest, locationCallback);

                FindViewById <TextView>(Resource.Id.txtStatus).Text = $"Status: Tracking";
            }
            else
            {
                FindViewById <TextView>(Resource.Id.txtStatus).Text = $"Status: Permission not granted";
            }
        }
コード例 #26
0
        Covid19LocationListener()
        {
            if (IsGooglePlayServicesInstalled())
            {
                fusedLocationProviderClient = LocationServices.GetFusedLocationProviderClient(Application.Context);
                fusedLocationProviderClient.GetLastLocationAsync().ContinueWith(task =>
                {
                    //Location = task.Result;
                });
                LocationRequest locationRequest = new LocationRequest()
                                                  .SetPriority(LocationRequest.PriorityHighAccuracy)
                                                  .SetInterval(60 * 1000 * 5)
                                                  .SetFastestInterval(60 * 1000 * 2);
                try
                {
                    fusedLocationProviderClient.RequestLocationUpdatesAsync(locationRequest, this);
                }catch (Exception e)
                {
                }
            }
            else
            {
                locationManager = Application.Context.GetSystemService(Context.LocationService) as LocationManager;
                var locationCriteria = new Criteria();

                locationCriteria.Accuracy         = Accuracy.Fine;
                locationCriteria.PowerRequirement = Power.Medium;

                locationProvider = locationManager.GetBestProvider(locationCriteria, true);
                if (locationManager.IsProviderEnabled(locationProvider))
                {
                    Location = locationManager.GetLastKnownLocation(locationProvider);
                    try
                    {
                        locationManager.RequestLocationUpdates(locationProvider, 10000, 20, this);
                    }catch (Exception e)
                    {
                    }
                }
            }
        }
コード例 #27
0
        public override async void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
        {
            if (requestCode == RC_LAST_LOCATION_PERMISSION_CHECK || requestCode == RC_LOCATION_UPDATES_PERMISSION_CHECK)
            {
                if (grantResults.Length == 1 && grantResults[0] == Permission.Granted)
                {
                    await _fusedLocationProviderClient.RequestLocationUpdatesAsync(_locationRequest, new FusedLocationProviderCallback(this));
                }
                else
                {
                    Toast.MakeText(this, "Error receiving GPS permissions", ToastLength.Long);
                    return;
                }
            }
            else
            {
                Log.Debug("FusedLocationProviderSample", "Don't know how to handle requestCode " + requestCode);
            }

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
コード例 #28
0
        protected override async void OnResume()
        {
            base.OnResume();

            // Subscribe for location updates
            locationCallback.LocationResult += LocationCallback_LocationResult;

            // Build our location request setting interval, priority, etc
            var locationRequest = new LocationRequest()
                                  .SetInterval(10000)
                                  .SetFastestInterval(1000)
                                  .SetPriority(LocationRequest.PriorityHighAccuracy);

            // Start receiving location updates
            await fusedClient.RequestLocationUpdatesAsync(locationRequest, locationCallback);

            // Get the last known location so we can show the user something immediately
            var lastLocation = await fusedClient.GetLastLocationAsync();

            if (lastLocation != null)
            {
                textLastLocation.Text = DescribeLocation(lastLocation);
            }
        }
コード例 #29
0
        private async Task UpdateLocation()
        {
            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) != Permission.Granted &&
                ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessCoarseLocation) != Permission.Granted)
            {
                RequestPermissions(new String[] { Manifest.Permission.AccessCoarseLocation, Manifest.Permission.AccessFineLocation },
                                   PERMISSION_LOCATION_REQUEST_CODE);
                return;
            }

            Location location = null;

            if (WearableHelper.IsGooglePlayServicesInstalled && !WearableHelper.HasGPS)
            {
                location = await mFusedLocationClient.GetLastLocationAsync();

                if (location == null)
                {
                    var mLocationRequest = new LocationRequest();
                    mLocationRequest.SetInterval(10000);
                    mLocationRequest.SetFastestInterval(1000);
                    mLocationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
                    mLocationRequest.SetNumUpdates(1);
                    await mFusedLocationClient.RequestLocationUpdatesAsync(mLocationRequest, mLocCallback, null);

                    await mFusedLocationClient.FlushLocationsAsync();
                }
            }
            else
            {
                LocationManager locMan       = (LocationManager)GetSystemService(Context.LocationService);
                bool            isGPSEnabled = locMan.IsProviderEnabled(LocationManager.GpsProvider);
                bool            isNetEnabled = locMan.IsProviderEnabled(LocationManager.NetworkProvider);

                if (isGPSEnabled)
                {
                    location = locMan.GetLastKnownLocation(LocationManager.GpsProvider);

                    if (location == null)
                    {
                        location = locMan.GetLastKnownLocation(LocationManager.NetworkProvider);
                    }

                    if (location == null)
                    {
                        locMan.RequestSingleUpdate(LocationManager.GpsProvider, mLocListnr, null);
                    }
                }
                else if (isNetEnabled)
                {
                    location = locMan.GetLastKnownLocation(LocationManager.NetworkProvider);

                    if (location == null)
                    {
                        locMan.RequestSingleUpdate(LocationManager.NetworkProvider, mLocListnr, null);
                    }
                }
                else
                {
                    EnableControls(true);
                    RunOnUiThread(() =>
                    {
                        Toast.MakeText(this, Resource.String.error_retrieve_location, ToastLength.Short).Show();
                    });
                }
            }

            if (location != null)
            {
                mLocation = location;
                await FetchGeoLocation();
            }
        }
コード例 #30
0
        protected override IObservable <LocationRecorded> CreateStartLocationUpdates()
        {
            return(Observable.Create <LocationRecorded>(subj =>
            {
                CompositeDisposable disp = new CompositeDisposable();
                try
                {
                    if (mLocationRequest == null)
                    {
                        mLocationRequest = LocationRequest.Create();
                        mLocationRequest.SetPriority(LocationRequest.PriorityBalancedPowerAccuracy);
                        mLocationRequest.SetInterval(10000);
                        mLocationRequest.SetFastestInterval(5000);
                    }

                    var locationResults =
                        Observable.FromEventPattern <LocationCallbackResultEventArgs>
                        (
                            x => _myCallback.LocationResult += x,
                            x => _myCallback.LocationResult -= x
                        )
                        .SelectMany(lu => lu.EventArgs.Result.Locations)
                        .Select(lu => PositionFactory(lu))
                        .Where(lu => lu != null)
                        .StartWith((LocationRecorded)null)
                        .Catch((Exception exc) =>
                    {
                        return Observable.Throw <LocationRecorded>(exc);
                    });

                    var removeLocationUpdates =
                        Observable.Create <Unit>(subs =>
                    {
                        return
                        mFusedLocationClient
                        .RemoveLocationUpdatesAsync(_myCallback)
                        .ToObservable()
                        .CatchAndLog(ExceptionHandling, Unit.Default)
                        .Subscribe(subs);
                    })
                        .SubscribeOn(Scheduler.Dispatcher);

                    // GetLocationAvailabilityAsync() throws an ApiException
                    // if google play services aren't available
                    // so I don't currently see the point of checking that before requesting location updates
                    // since I feel like they will achieve the same thing at this point
                    // need to investigate where there might be divergent behavior between the two
                    Func <IObservable <bool> > requestUpdates = null;
                    requestUpdates = () =>
                                     // using from async to ensure it's lazy
                                     Observable.FromAsync(() => mFusedLocationClient
                                                          .RequestLocationUpdatesAsync(mLocationRequest, _myCallback)
                                                          )
                                     .Select(_ => true)
                                     .Do(_ =>
                    {
                        // successfully requesting updates so setup remove on unsubscribe.
                        // only want to wire this up if requesting updates is successful
                        Disposable.Create(() =>
                        {
                            removeLocationUpdates
                            .Subscribe();
                        })
                        .DisposeWith(disp);
                    })

                                     // error trying to request updates
                                     .Catch((ApiException api) =>
                    {
                        var activationException =
                            new LocationActivationException
                            (
                                ActivationFailedReasons.CheckExceptionOnPlatform,
                                api
                            );

                        ExceptionHandling
                        .LogException(activationException);

                        // wait for a change in location availibility to occur
                        return
                        Observable.FromEventPattern <LocationCallbackAvailabilityEventArgs>
                        (
                            x => _myCallback.LocationAvailability += x,
                            x => _myCallback.LocationAvailability -= x
                        )
                        .Select(changed => changed.EventArgs.Availability.IsLocationAvailable)
                        .Log("Availability")
                        .Where(x => x)
                        .Take(1)
                        .SelectMany(_ => requestUpdates());
                    })
                                     // unknown exception occurred :-(
                                     .Catch((Exception exc) =>
                    {
                        return Observable.Throw <bool>(exc);
                    })
                                     .StartWith(false);

                    Observable.CombineLatest(
                        locationResults,
                        requestUpdates(),
                        (result, requestUpdatesActive) =>
                    {
                        IsListeningForChangesImperative = true;

                        if (!requestUpdatesActive)
                        {
                            return Observable.Empty <LocationRecorded>();
                        }

                        if (result == null)
                        {
                            return Observable.Empty <LocationRecorded>();
                        }

                        return Observable.Return(result);
                    })
                    .SelectMany(x => x)
                    .Subscribe(subj)
                    .DisposeWith(disp);

                    Disposable.Create(() =>
                    {
                        IsListeningForChangesImperative = false;
                    })
                    .DisposeWith(disp);

                    return disp;
                }
                catch (Exception exc)
                {
                    subj.OnError(exc);
                    disp.Dispose();
                }

                return Disposable.Empty;
            }
                                                        )
                   .SubscribeOn(Scheduler.Dispatcher));
        }