/// <inheritdoc/>
        public async Task<Position> GetPositionAsync(int timeoutMilliseconds = Timeout.Infinite, CancellationToken? cancelToken = null, bool includeHeading = false)
        {
            var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permissions.Abstractions.Permission.Location).ConfigureAwait(false);
            if (status != Permissions.Abstractions.PermissionStatus.Granted)
            {
                Console.WriteLine("Currently does not have Location permissions, requesting permissions");

                var request = await CrossPermissions.Current.RequestPermissionsAsync(Permissions.Abstractions.Permission.Location);

                if (request[Permissions.Abstractions.Permission.Location] != Permissions.Abstractions.PermissionStatus.Granted)
                {
                    Console.WriteLine("Location permission denied, can not get positions async.");
                    return null;
                }
                providers = manager.GetProviders(enabledOnly: false).Where(s => s != LocationManager.PassiveProvider).ToArray();
            }

            if (providers.Length == 0)
            {
                providers = manager.GetProviders(enabledOnly: false).Where(s => s != LocationManager.PassiveProvider).ToArray();
            }


            if (timeoutMilliseconds <= 0 && timeoutMilliseconds != Timeout.Infinite)
                throw new ArgumentOutOfRangeException("timeoutMilliseconds", "timeout must be greater than or equal to 0");

            if (!cancelToken.HasValue)
                cancelToken = CancellationToken.None;


            var tcs = new TaskCompletionSource<Position>();

            if (!IsListening)
            {
                GeolocationSingleListener singleListener = null;
                singleListener = new GeolocationSingleListener((float)DesiredAccuracy, timeoutMilliseconds, providers.Where(manager.IsProviderEnabled),
                    finishedCallback: () =>
                {
                    for (int i = 0; i < providers.Length; ++i)
                        manager.RemoveUpdates(singleListener);
                });

                if (cancelToken != CancellationToken.None)
                {
                    cancelToken.Value.Register(() =>
                    {
                        singleListener.Cancel();

                        for (int i = 0; i < providers.Length; ++i)
                            manager.RemoveUpdates(singleListener);
                    }, true);
                }

                try
                {
                    Looper looper = Looper.MyLooper() ?? Looper.MainLooper;

                    int enabled = 0;
                    for (int i = 0; i < providers.Length; ++i)
                    {
                        if (manager.IsProviderEnabled(providers[i]))
                            enabled++;

                        manager.RequestLocationUpdates(providers[i], 0, 0, singleListener, looper);
                    }

                    if (enabled == 0)
                    {
                        for (int i = 0; i < providers.Length; ++i)
                            manager.RemoveUpdates(singleListener);

                        tcs.SetException(new GeolocationException(GeolocationError.PositionUnavailable));
                        return await tcs.Task.ConfigureAwait(false);
                    }
                }
                catch (Java.Lang.SecurityException ex)
                {
                    tcs.SetException(new GeolocationException(GeolocationError.Unauthorized, ex));
                    return await tcs.Task.ConfigureAwait(false);
                }

                return await singleListener.Task.ConfigureAwait(false);
            }

            // If we're already listening, just use the current listener
            lock (positionSync)
            {
                if (lastPosition == null)
                {
                    if (cancelToken != CancellationToken.None)
                    {
                        cancelToken.Value.Register(() => tcs.TrySetCanceled());
                    }

                    EventHandler<PositionEventArgs> gotPosition = null;
                    gotPosition = (s, e) =>
                    {
                        tcs.TrySetResult(e.Position);
                        PositionChanged -= gotPosition;
                    };

                    PositionChanged += gotPosition;
                }
                else
                {
                    tcs.SetResult(lastPosition);
                }
            }

            return await tcs.Task.ConfigureAwait(false);
        }
Exemple #2
0
        /// <inheritdoc/>
        public async Task <Position> GetPositionAsync(int timeoutMilliseconds = Timeout.Infinite, CancellationToken?cancelToken = null, bool includeHeading = false)
        {
            var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permissions.Abstractions.Permission.Location).ConfigureAwait(false);

            if (status != Permissions.Abstractions.PermissionStatus.Granted)
            {
                Console.WriteLine("Currently does not have Location permissions, requesting permissions");

                var request = await CrossPermissions.Current.RequestPermissionsAsync(Permissions.Abstractions.Permission.Location);

                if (request[Permissions.Abstractions.Permission.Location] != Permissions.Abstractions.PermissionStatus.Granted)
                {
                    Console.WriteLine("Location permission denied, can not get positions async.");
                    return(null);
                }
                providers = manager.GetProviders(enabledOnly: false).Where(s => s != LocationManager.PassiveProvider).ToArray();
            }

            if (providers.Length == 0)
            {
                providers = manager.GetProviders(enabledOnly: false).Where(s => s != LocationManager.PassiveProvider).ToArray();
            }


            if (timeoutMilliseconds <= 0 && timeoutMilliseconds != Timeout.Infinite)
            {
                throw new ArgumentOutOfRangeException("timeoutMilliseconds", "timeout must be greater than or equal to 0");
            }

            if (!cancelToken.HasValue)
            {
                cancelToken = CancellationToken.None;
            }


            var tcs = new TaskCompletionSource <Position>();

            if (!IsListening)
            {
                GeolocationSingleListener singleListener = null;
                singleListener = new GeolocationSingleListener((float)DesiredAccuracy, timeoutMilliseconds, providers.Where(manager.IsProviderEnabled),
                                                               finishedCallback: () =>
                {
                    for (int i = 0; i < providers.Length; ++i)
                    {
                        manager.RemoveUpdates(singleListener);
                    }
                });

                if (cancelToken != CancellationToken.None)
                {
                    cancelToken.Value.Register(() =>
                    {
                        singleListener.Cancel();

                        for (int i = 0; i < providers.Length; ++i)
                        {
                            manager.RemoveUpdates(singleListener);
                        }
                    }, true);
                }

                try
                {
                    Looper looper = Looper.MyLooper() ?? Looper.MainLooper;

                    int enabled = 0;
                    for (int i = 0; i < providers.Length; ++i)
                    {
                        if (manager.IsProviderEnabled(providers[i]))
                        {
                            enabled++;
                        }

                        manager.RequestLocationUpdates(providers[i], 0, 0, singleListener, looper);
                    }

                    if (enabled == 0)
                    {
                        for (int i = 0; i < providers.Length; ++i)
                        {
                            manager.RemoveUpdates(singleListener);
                        }

                        tcs.SetException(new GeolocationException(GeolocationError.PositionUnavailable));
                        return(await tcs.Task.ConfigureAwait(false));
                    }
                }
                catch (Java.Lang.SecurityException ex)
                {
                    tcs.SetException(new GeolocationException(GeolocationError.Unauthorized, ex));
                    return(await tcs.Task.ConfigureAwait(false));
                }

                return(await singleListener.Task.ConfigureAwait(false));
            }

            // If we're already listening, just use the current listener
            lock (positionSync)
            {
                if (lastPosition == null)
                {
                    if (cancelToken != CancellationToken.None)
                    {
                        cancelToken.Value.Register(() => tcs.TrySetCanceled());
                    }

                    EventHandler <PositionEventArgs> gotPosition = null;
                    gotPosition = (s, e) =>
                    {
                        tcs.TrySetResult(e.Position);
                        PositionChanged -= gotPosition;
                    };

                    PositionChanged += gotPosition;
                }
                else
                {
                    tcs.SetResult(lastPosition);
                }
            }

            return(await tcs.Task.ConfigureAwait(false));
        }
        /// <inheritdoc/>
        public async Task <Position> GetPositionAsync(TimeSpan?timeout, CancellationToken?cancelToken = null, bool includeHeading = false)
        {
            var timeoutMilliseconds = timeout.HasValue ? (int)timeout.Value.TotalMilliseconds : Timeout.Infinite;

            if (timeoutMilliseconds <= 0 && timeoutMilliseconds != Timeout.Infinite)
            {
                throw new ArgumentOutOfRangeException(nameof(timeout), "timeout must be greater than or equal to 0");
            }

            if (!cancelToken.HasValue)
            {
                cancelToken = CancellationToken.None;
            }

            var hasPermission = await CheckPermissions();

            if (!hasPermission)
            {
                return(null);
            }

            var tcs = new TaskCompletionSource <Position>();

            if (!IsListening)
            {
                var providers = Providers;
                GeolocationSingleListener singleListener = null;
                singleListener = new GeolocationSingleListener(Manager, (float)DesiredAccuracy, timeoutMilliseconds, providers.Where(Manager.IsProviderEnabled),
                                                               finishedCallback: () =>
                {
                    for (int i = 0; i < providers.Length; ++i)
                    {
                        Manager.RemoveUpdates(singleListener);
                    }
                });

                if (cancelToken != CancellationToken.None)
                {
                    cancelToken.Value.Register(() =>
                    {
                        singleListener.Cancel();

                        for (int i = 0; i < providers.Length; ++i)
                        {
                            Manager.RemoveUpdates(singleListener);
                        }
                    }, true);
                }

                try
                {
                    var looper = Looper.MyLooper() ?? Looper.MainLooper;

                    int enabled = 0;
                    for (int i = 0; i < providers.Length; ++i)
                    {
                        if (Manager.IsProviderEnabled(providers[i]))
                        {
                            enabled++;
                        }

                        Manager.RequestLocationUpdates(providers[i], 0, 0, singleListener, looper);
                    }

                    if (enabled == 0)
                    {
                        for (int i = 0; i < providers.Length; ++i)
                        {
                            Manager.RemoveUpdates(singleListener);
                        }

                        tcs.SetException(new GeolocationException(GeolocationError.PositionUnavailable));
                        return(await tcs.Task);
                    }
                }
                catch (Java.Lang.SecurityException ex)
                {
                    tcs.SetException(new GeolocationException(GeolocationError.Unauthorized, ex));
                    return(await tcs.Task);
                }

                return(await singleListener.Task);
            }

            // If we're already listening, just use the current listener
            lock (positionSync)
            {
                if (lastPosition == null)
                {
                    if (cancelToken != CancellationToken.None)
                    {
                        cancelToken.Value.Register(() => tcs.TrySetCanceled());
                    }

                    EventHandler <PositionEventArgs> gotPosition = null;
                    gotPosition = (s, e) =>
                    {
                        tcs.TrySetResult(e.Position);
                        PositionChanged -= gotPosition;
                    };

                    PositionChanged += gotPosition;
                }
                else
                {
                    tcs.SetResult(lastPosition);
                }
            }

            return(await tcs.Task);
        }