Esempio n. 1
0
        static async Task <IEnumerable <FilePickerResult> > PlatformPickAsync(PickOptions options, bool allowMultiple = false)
        {
            // we only need the permission when accessing the file, but it's more natural
            // to ask the user first, then show the picker.
            await Permissions.RequestAsync <Permissions.StorageRead>();

            // Essentials supports >= API 19 where this action is available
            var action = Intent.ActionOpenDocument;

            var intent = new Intent(action);

            intent.SetType("*/*");
            intent.AddFlags(ActivityFlags.GrantPersistableUriPermission);
            intent.PutExtra(Intent.ExtraAllowMultiple, allowMultiple);

            var allowedTypes = options?.FileTypes?.Value?.ToArray();

            if (allowedTypes?.Length > 0)
            {
                intent.PutExtra(Intent.ExtraMimeTypes, allowedTypes);
            }

            var pickerIntent = Intent.CreateChooser(intent, options?.PickerTitle ?? "Select file");

            try
            {
                var result = await IntermediateActivity.StartAsync(pickerIntent, requestCodeFilePicker);

                var resultList = new List <FilePickerResult>();

                var clipData = new List <global::Android.Net.Uri>();

                if (result.ClipData == null)
                {
                    clipData.Add(result.Data);
                }
                else
                {
                    for (var i = 0; i < result.ClipData.ItemCount; i++)
                    {
                        clipData.Add(result.ClipData.GetItemAt(i).Uri);
                    }
                }

                foreach (var contentUri in clipData)
                {
                    Platform.AppContext.ContentResolver.TakePersistableUriPermission(
                        contentUri,
                        ActivityFlags.GrantReadUriPermission);

                    resultList.Add(new FilePickerResult(contentUri));
                }

                return(resultList);
            }
            catch (OperationCanceledException)
            {
                return(null);
            }
        }
        static async Task <FileResult> PlatformPickAsync(MediaPickerOptions options, bool photo)
        {
            // We only need the permission when accessing the file, but it's more natural
            // to ask the user first, then show the picker.
            await Permissions.RequestAsync <Permissions.StorageRead>();

            var intent = new Intent(Intent.ActionGetContent);

            intent.SetType(photo ? FileSystem.MimeTypes.ImageAll : FileSystem.MimeTypes.VideoAll);

            var pickerIntent = Intent.CreateChooser(intent, options?.Title);

            try
            {
                string path = null;
                void OnResult(Intent intent)
                {
                    // The uri returned is only temporary and only lives as long as the Activity that requested it,
                    // so this means that it will always be cleaned up by the time we need it because we are using
                    // an intermediate activity.

                    path = FileSystem.EnsurePhysicalPath(intent.Data);
                }

                await IntermediateActivity.StartAsync(pickerIntent, Platform.requestCodeMediaPicker, onResult : OnResult);

                return(new FileResult(path));
            }
            catch (OperationCanceledException)
            {
                return(null);
            }
        }
Esempio n. 3
0
        static async Task <Location> PlatformLocationAsync(GeolocationRequest request, CancellationToken cancellationToken)
        {
            await Permissions.RequestAsync <Permissions.LocationWhenInUse>();

            var geolocator = new Geolocator
            {
                DesiredAccuracyInMeters = request.PlatformDesiredAccuracy
            };

            CheckStatus(geolocator.LocationStatus);

            cancellationToken = Utils.TimeoutToken(cancellationToken, request.Timeout);

            var location = await geolocator.GetGeopositionAsync().AsTask(cancellationToken);

            return(location?.Coordinate?.ToLocation());

            void CheckStatus(PositionStatus status)
            {
                switch (status)
                {
                case PositionStatus.Disabled:
                case PositionStatus.NotAvailable:
                    throw new FeatureNotEnabledException("Location services are not enabled on device.");
                }
            }
        }
Esempio n. 4
0
        internal virtual async Task <Stream> PlatformOpenReadAsync()
        {
            await Permissions.RequestAsync <Permissions.StorageRead>();

            var stream = File.Open(FullPath, FileMode.Open, FileAccess.Read);

            return(Task.FromResult <Stream>(stream).Result);
        }
        static async Task <IEnumerable <FileResult> > PlatformPickAsync(PickOptions options, bool allowMultiple = false)
        {
            // we only need the permission when accessing the file, but it's more natural
            // to ask the user first, then show the picker.
            await Permissions.RequestAsync <Permissions.StorageRead>();

            // Essentials supports >= API 19 where this action is available
            var action = Intent.ActionOpenDocument;

            var intent = new Intent(action);

            intent.SetType(FileSystem.MimeTypes.All);
            intent.PutExtra(Intent.ExtraAllowMultiple, allowMultiple);

            var allowedTypes = options?.FileTypes?.Value?.ToArray();

            if (allowedTypes?.Length > 0)
            {
                intent.PutExtra(Intent.ExtraMimeTypes, allowedTypes);
            }

            var pickerIntent = Intent.CreateChooser(intent, options?.PickerTitle ?? "Select file");

            try
            {
                var resultList = new List <FileResult>();
                void OnResult(Intent intent)
                {
                    // The uri returned is only temporary and only lives as long as the Activity that requested it,
                    // so this means that it will always be cleaned up by the time we need it because we are using
                    // an intermediate activity.

                    if (intent.ClipData == null)
                    {
                        var path = FileSystem.EnsurePhysicalPath(intent.Data);
                        resultList.Add(new FileResult(path));
                    }
                    else
                    {
                        for (var i = 0; i < intent.ClipData.ItemCount; i++)
                        {
                            var uri  = intent.ClipData.GetItemAt(i).Uri;
                            var path = FileSystem.EnsurePhysicalPath(uri);
                            resultList.Add(new FileResult(path));
                        }
                    }
                }

                await IntermediateActivity.StartAsync(pickerIntent, Platform.requestCodeFilePicker, onResult : OnResult);

                return(resultList);
            }
            catch (OperationCanceledException)
            {
                return(null);
            }
        }
 /// <inheritdoc />
 public async Task <PermissionStatus> RequestPermissionsAsync <T>()
     where T : BasePermission, new()
 {
     return(await MainThread.InvokeOnMainThreadAsync(async() =>
     {
         var result = await EssentialsPermissions.RequestAsync <T>().ConfigureAwait(false);
         return result.ToPermissionStatus();
     }));
 }
        static async Task CheckSupportAsync()
        {
            if (!IsSupported)
            {
                throw new FeatureNotSupportedException();
            }

            await Permissions.RequestAsync <Permissions.Flashlight>();
        }
Esempio n. 8
0
        static async Task <Location> PlatformLocationAsync(GeolocationRequest request, CancellationToken cancellationToken)
        {
            if (!CLLocationManager.LocationServicesEnabled)
            {
                throw new FeatureNotEnabledException("Location services are not enabled on device.");
            }

            await Permissions.RequestAsync <Permissions.LocationWhenInUse>();

            // the location manager requires an active run loop
            // so just use the main loop
            CLLocationManager manager = null;

            NSRunLoop.Main.InvokeOnMainThread(() => manager = new CLLocationManager());

            var tcs = new TaskCompletionSource <CLLocation>(manager);

            var listener = new SingleLocationListener();

            listener.LocationHandler += HandleLocation;

            cancellationToken = Utils.TimeoutToken(cancellationToken, request.Timeout);
            cancellationToken.Register(Cancel);

            manager.DesiredAccuracy = request.PlatformDesiredAccuracy;
            manager.Delegate        = listener;

#if __IOS__
            // we're only listening for a single update
            manager.PausesLocationUpdatesAutomatically = false;
#endif

            manager.StartUpdatingLocation();

            var clLocation = await tcs.Task;

            return(clLocation?.ToLocation());

            void HandleLocation(CLLocation location)
            {
                manager.StopUpdatingLocation();
                tcs.TrySetResult(location);
            }

            void Cancel()
            {
                manager.StopUpdatingLocation();
                tcs.TrySetResult(null);
            }
        }
Esempio n. 9
0
        static async Task <Location> PlatformLastKnownLocationAsync()
        {
            if (!CLLocationManager.LocationServicesEnabled)
            {
                throw new FeatureNotEnabledException("Location services are not enabled on device.");
            }

            await Permissions.RequestAsync <Permissions.LocationWhenInUse>();

            var manager  = new CLLocationManager();
            var location = manager.Location;

            return(location?.ToLocation());
        }
        /// <inheritdoc />
        public async Task <PermissionStatus> RequestPermissionsAsync <T>()
            where T : BasePermission, new()
        {
            return(await MainThread.InvokeOnMainThreadAsync(async() =>
            {
                if (typeof(T) == typeof(NotificationsPermission))
                {
                    return await RequestNotificationPermissionAsync().ConfigureAwait(false);
                }

                var result = await EssentialsPermissions.RequestAsync <T>().ConfigureAwait(false);

                return result.ToPermissionStatus();
            }));
        }
        static async Task <Location> PlatformLastKnownLocationAsync()
        {
            await Permissions.RequestAsync <Permissions.LocationWhenInUse>();

            var             lm           = Platform.LocationManager;
            AndroidLocation bestLocation = null;

            foreach (var provider in lm.GetProviders(true))
            {
                var location = lm.GetLastKnownLocation(provider);

                if (location != null && IsBetterLocation(location, bestLocation))
                {
                    bestLocation = location;
                }
            }

            return(bestLocation?.ToLocation());
        }
Esempio n. 12
0
        static async Task <FileResult> PlatformPickAsync(MediaPickerOptions options, bool photo)
        {
            // we only need the permission when accessing the file, but it's more natural
            // to ask the user first, then show the picker.
            await Permissions.RequestAsync <Permissions.StorageRead>();

            var intent = new Intent(Intent.ActionGetContent);

            intent.SetType(photo ? "image/*" : "video/*");

            var pickerIntent = Intent.CreateChooser(intent, options?.Title);

            try
            {
                var result = await IntermediateActivity.StartAsync(pickerIntent, Platform.requestCodeMediaPicker);

                return(new FileResult(result.Data));
            }
            catch (OperationCanceledException)
            {
                return(null);
            }
        }
        static async Task <Location> PlatformLocationAsync(GeolocationRequest request, CancellationToken cancellationToken)
        {
            await Permissions.RequestAsync <Permissions.LocationWhenInUse>();

            var locationManager = Platform.LocationManager;

            var enabledProviders = locationManager.GetProviders(true);
            var hasProviders     = enabledProviders.Any(p => !ignoredProviders.Contains(p));

            if (!hasProviders)
            {
                throw new FeatureNotEnabledException("Location services are not enabled on device.");
            }

            // get the best possible provider for the requested accuracy
            var providerInfo = GetBestProvider(locationManager, request.DesiredAccuracy);

            // if no providers exist, we can't get a location
            // let's punt and try to get the last known location
            if (string.IsNullOrEmpty(providerInfo.Provider))
            {
                return(await GetLastKnownLocationAsync());
            }

            var tcs = new TaskCompletionSource <AndroidLocation>();

            var allProviders = locationManager.GetProviders(false);

            var providers = new List <string>();

            if (allProviders.Contains(LocationManager.GpsProvider))
            {
                providers.Add(LocationManager.GpsProvider);
            }
            if (allProviders.Contains(LocationManager.NetworkProvider))
            {
                providers.Add(LocationManager.NetworkProvider);
            }

            if (providers.Count == 0)
            {
                providers.Add(providerInfo.Provider);
            }

            var listener = new SingleLocationListener(locationManager, providerInfo.Accuracy, providers);

            listener.LocationHandler = HandleLocation;

            cancellationToken = Utils.TimeoutToken(cancellationToken, request.Timeout);
            cancellationToken.Register(Cancel);

            // start getting location updates
            // make sure to use a thread with a looper
            var looper = Looper.MyLooper() ?? Looper.MainLooper;

            foreach (var provider in providers)
            {
                locationManager.RequestLocationUpdates(provider, 0, 0, listener, looper);
            }

            var androidLocation = await tcs.Task;

            if (androidLocation == null)
            {
                return(null);
            }

            return(androidLocation.ToLocation());

            void HandleLocation(AndroidLocation location)
            {
                RemoveUpdates();
                tcs.TrySetResult(location);
            }

            void Cancel()
            {
                RemoveUpdates();
                tcs.TrySetResult(listener.BestLocation);
            }

            void RemoveUpdates()
            {
                for (var i = 0; i < providers.Count; i++)
                {
                    locationManager.RemoveUpdates(listener);
                }
            }
        }
Esempio n. 14
0
        static async Task <Location> PlatformLastKnownLocationAsync()
        {
            await Permissions.RequestAsync(PermissionType.LocationWhenInUse);

            return(lastKnownLocation);
        }
        static async Task <Location> PlatformLocationAsync(GeolocationRequest request, CancellationToken cancellationToken)
        {
            await Permissions.RequestAsync <Permissions.LocationWhenInUse>();

            Locator service = null;
            var     gps     = Platform.GetFeatureInfo <bool>("location.gps");
            var     wps     = Platform.GetFeatureInfo <bool>("location.wps");

            if (gps)
            {
                if (wps)
                {
                    service = new Locator(LocationType.Hybrid);
                }
                else
                {
                    service = new Locator(LocationType.Gps);
                }
            }
            else
            {
                if (wps)
                {
                    service = new Locator(LocationType.Wps);
                }
                else
                {
                    service = new Locator(LocationType.Passive);
                }
            }

            var tcs = new TaskCompletionSource <bool>();

            cancellationToken = Utils.TimeoutToken(cancellationToken, request.Timeout);
            cancellationToken.Register(() =>
            {
                service?.Stop();
                tcs.TrySetResult(false);
            });

            double KmToMetersPerSecond(double km) => km * 0.277778;

            service.LocationChanged += (s, e) =>
            {
                if (e.Location != null)
                {
                    lastKnownLocation.Accuracy  = e.Location.Accuracy;
                    lastKnownLocation.Altitude  = e.Location.Altitude;
                    lastKnownLocation.Course    = e.Location.Direction;
                    lastKnownLocation.Latitude  = e.Location.Latitude;
                    lastKnownLocation.Longitude = e.Location.Longitude;
                    lastKnownLocation.Speed     = KmToMetersPerSecond(e.Location.Speed);
                    lastKnownLocation.Timestamp = e.Location.Timestamp;
                }
                service?.Stop();
                tcs.TrySetResult(true);
            };
            service.Start();

            await tcs.Task;

            return(lastKnownLocation);
        }