Exemple #1
0
        public void OnConnected(Bundle connectionHint)
        {
            var lastLocation = LocationServices.FusedLocationApi.GetLastLocation(_googleAPIClient);

            if (lastLocation == null)
            {
                _locationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
                _locationRequest.SetNumUpdates(1);
            }
            else
            {
                this.OnLocationChanged(lastLocation);
            }

            LocationServices.FusedLocationApi.RequestLocationUpdates(_googleAPIClient, _locationRequest, this);
        }
 /// <summary>
 /// Starts the google services polling new location events.
 /// </summary>
 private void StartGoogleServicesPolling()
 {
     Log.V(this, "Starting automatic location polling");
     isPolling = true;
     altitudeProvider.StartUpdates();
     altitudeProvider.onAltitudeEvent += OnAltitudeEvent;
     altitudeProvider.PostRequestSingleLocation();
     if (client != null && client.IsConnected)
     {
         request = new LocationRequest();
         request.SetFastestInterval((long)TimeSpan.FromMinutes(0.5).TotalMilliseconds);
         request.SetInterval((long)TimeSpan.FromMinutes(1.5).TotalMilliseconds);
         request.SetNumUpdates(60);
         request.SetPriority(LocationRequest.PriorityBalancedPowerAccuracy);
         LocationServices.FusedLocationApi.RequestLocationUpdates(client, request, this);
     }
 }
Exemple #3
0
        private void SetLocationRequest(LocationRequest request)
        {
            TableLayout table = FindViewById <TableLayout>(Resource.Id.callback_table_layout_show);
            Dictionary <string, string> paramList = new Dictionary <string, string>();

            TableRow[] rows = new TableRow[table.ChildCount];
            for (int i = 0; i < rows.Length; i++)
            {
                rows[i] = (TableRow)table.GetChildAt(i);
                paramList[((TextView)rows[i].GetChildAt(0)).Text] = ((EditText)rows[i].GetChildAt(1)).Text;
            }
            request.SetPriority(int.Parse(paramList[LocationRequestConstants.Priority]));
            request.SetInterval(long.Parse(paramList[LocationRequestConstants.Interval]));
            request.SetFastestInterval(long.Parse(paramList[LocationRequestConstants.FastestInterval]));
            request.SetExpirationTime(long.Parse(paramList[LocationRequestConstants.ExpirationTime]));
            request.SetExpirationDuration(long.Parse(paramList[LocationRequestConstants.ExpirationDuration]));
            request.SetNumUpdates(int.Parse(paramList[LocationRequestConstants.NumUpdates]));
            request.SetSmallestDisplacement(float.Parse(paramList[LocationRequestConstants.SmallestDisplacement]));
            request.SetMaxWaitTime(long.Parse(paramList[LocationRequestConstants.MaxWaitTime]));
            request.SetNeedAddress(bool.Parse(paramList[LocationRequestConstants.NeedAddress]));
            request.SetLanguage(paramList[LocationRequestConstants.Language]);
            request.SetCountryCode(paramList[LocationRequestConstants.CountryCode]);
        }
        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();
            }
        }
        private async void OnClickGetCurrentLocation(object sender, EventArgs eventArgs)
        {
            string Tag = "RequestLocationUpdates";

            if (locationRequest.NumUpdates != 1)
            {
                locationRequest.SetNumUpdates(1);
            }
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
            builder.AddLocationRequest(locationRequest);
            LocationSettingsRequest request = builder.Build();
            //Before requesting location update, invoke CheckLocationSettings to check device settings.
            var locationSettingsResponseTask = settingsClient.CheckLocationSettingsAsync(request);

            try
            {
                await locationSettingsResponseTask;
                if (locationSettingsResponseTask.IsCompleted && locationSettingsResponseTask != null)
                {
                    LocationSettingsResponse response = locationSettingsResponseTask.Result;
                    var requestLocationUpdatesTask    = fusedLocationProviderClient.RequestLocationUpdatesAsync(locationRequest, locationCallback, Looper.MainLooper);
                    try
                    {
                        await requestLocationUpdatesTask;
                        if (requestLocationUpdatesTask.IsCompleted)
                        {
                            log.Info(Tag, "RequestLocationUpdates with callback succeeded.");
                        }
                        else
                        {
                            log.Error(Tag, $"RequestLocationUpdates with callback failed: {requestLocationUpdatesTask.Exception.Message}");
                        }
                    }
                    catch (Exception e)
                    {
                        log.Error(Tag, $"RequestLocationUpdates with callback failed: {e.Message}");
                    }
                }
                else
                {
                    var exception = locationSettingsResponseTask.Exception;
                    log.Error(Tag, $"CheckLocationSetting Failed: {exception.Message}");
                }
            }
            catch (Exception e)
            {
                if (e is ApiException apiException)
                {
                    log.Error(Tag, $"CheckLocationSetting Failed. ErrorMessage: {apiException.Message} ErrorCode: {apiException.StatusCode}");

                    int statuesCode = apiException.StatusCode;
                    if (statuesCode == LocationSettingsStatusCodes.ResolutionRequired)
                    {
                        try
                        {
                            //When the StartResolutionForResult is invoked, a dialog box is displayed, asking you to open the corresponding permission.
                            ResolvableApiException resolvableApiException = (ResolvableApiException)e;
                            resolvableApiException.StartResolutionForResult(this, 0);
                        }
                        catch (IntentSender.SendIntentException sendIntentException)
                        {
                            log.Error(Tag, "PendingIntent unable to execute request.");
                        }
                    }
                }
                else
                {
                    log.Error(Tag, $"CheckLocationSetting Failed: {e.Message}");
                }
            }
        }