Ejemplo n.º 1
0
        static async Task <FileInfo[]> PickPhotoCore(bool enableMultipleSelection, OnError errorAction = OnError.Alert)
        {
            if (!SupportsPickingPhoto())
            {
                await errorAction.Apply("Your device does not support picking photos.");

                return(null);
            }

            if (!await Permission.Albums.IsRequestGranted())
            {
                await SuggestLaunchingSettings(errorAction, "Permission was denied to access the device gallery.");

                return(null);
            }

            try
            {
                return(await Thread.UI.Run(() => DoPickPhoto(enableMultipleSelection)));
            }
            catch (Exception ex)
            {
                await errorAction.Apply("Failed to pick a photo: " + ex.Message);

                return(null);
            }
        }
Ejemplo n.º 2
0
 public static async Task SendSMS(SMS message, OnError errorAction = OnError.Alert)
 {
     if (!CanSendSMS)
     {
         await errorAction.Apply("Your device does not support sending SMS.");
     }
     else
     {
         try { await SMSHelper.ComposeAsync(message); }
         catch (Exception ex) { await errorAction.Apply("Failed to send SMS: " + ex.Message); }
     }
 }
Ejemplo n.º 3
0
 /// <summary>Send an email using the default email application on the device.</summary>
 public static async Task SendEmail(EmailMessage message, OnError errorAction = OnError.Alert)
 {
     if (!CanSendEmail)
     {
         await errorAction.Apply("Your device does not support sending emails.");
     }
     else
     {
         try { await DoSendEmail(message); }
         catch (Exception ex) { await errorAction.Apply("Failed to send email: " + ex.Message); }
     }
 }
Ejemplo n.º 4
0
        /// <summary>Returns the current user position.</summary>
        /// <param name="desiredAccuracy">In meters</param>
        /// <param name="timeout">Milliseconds</param>
        /// <param name="silently">If set to true, then the position will only be returned if it's available and request is previously granted but there will be no user interaction (this can only be used in combination with OnError.Ignore or Throw). If set to false (default) then if necessary, the user will be prompted for granting permission, and in any case the specified error action will apply when there i any problem (GPS not supported or enabled on the device, permission denied, general error, etc.)</param>
        public static async Task <GeoPosition> GetCurrentPosition(double desiredAccuracy = TEN_METERS, int timeout = FIVE_SECONDS, bool silently = false, OnError errorAction = OnError.Alert)
        {
            if (silently && errorAction != OnError.Ignore && errorAction != OnError.Throw)
            {
                throw new Exception("If you want to get the DeviceLocation silently, ErrorAction must also be Ignore or Throw.");
            }

            await AskForPermission();

            if (!(await IsSupported()))
            {
                await errorAction.Apply("Geo DeviceLocation is not supported on your device.");

                return(null);
            }

            if (OS.Platform != DevicePlatform.IOS && !await IsEnabled())
            {
                var result = await Device.Permissions.Check(Permission.Location);

                if (result != PermissionResult.Granted)
                {
                    await errorAction.Apply("Geo DeviceLocation is not enabled on your device.");

                    return(null);
                }
            }

            if (silently && !await Permission.Location.IsGranted())
            {
                await errorAction.Apply("Permission is not already granted to access the current DeviceLocation.");

                return(null);
            }

            if (!await Permission.Location.IsRequestGranted())
            {
                await errorAction.Apply("Permission was not granted to access your current DeviceLocation.");

                return(null);
            }

            try
            {
                return(await Thread.UI.Run(() => TryGetCurrentPosition(desiredAccuracy, timeout)));
            }
            catch (Exception ex)
            {
                await errorAction.Apply(ex, "Failed to get current position.");

                return(null);
            }
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Make a phone call using the default dialer UI on the device.
 /// </summary>
 /// <param name="number">Number to phone</param>
 public static async Task PhoneCall(string number, string name = null, OnError errorAction = OnError.Alert)
 {
     if (!await Device.Permission.PhoneCall.IsRequestGranted())
     {
         await errorAction.Apply("Permission was denied to make a phone call.");
     }
     else
     {
         try { await DoMakePhoneCall(number, name); }
         catch (Exception ex)
         {
             await errorAction.Apply("Failed to call number " + number + ". " + ex.Message);
         }
     }
 }
Ejemplo n.º 6
0
        Task ExecuteSafe(Func <Task> execution, OnError errorAction, string errorMessage)
        {
            var task = new TaskCompletionSource <bool>();

            AudioThread.Post(async() =>
            {
                try
                {
                    await execution();
                    task.TrySetResult(true);
                }
                catch (Exception ex)
                {
                    if (errorAction == OnError.Throw)
                    {
                        task.TrySetException(ex);
                    }
                    else
                    {
                        await errorAction.Apply(ex, "Failed to play audio file");
                        task.TrySetResult(false);
                    }
                }
            });

            return(task.Task);
        }
Ejemplo n.º 7
0
        static async Task Turn(AVCaptureTorchMode mode, OnError errorAction)
        {
            using (var captureDevice = GetCamera())
            {
                if (captureDevice == null)
                {
                    throw new Exception("Camera device was not found.");
                }

                try
                {
                    captureDevice.LockForConfiguration(out var error);

                    if (error != null)
                    {
                        throw new Exception(error.Description);
                    }

                    if (captureDevice.TorchMode != mode)
                    {
                        captureDevice.TorchMode = mode;
                    }

                    captureDevice.UnlockForConfiguration();
                }
                catch (Exception ex) { await errorAction.Apply(ex); }
            }
        }
Ejemplo n.º 8
0
        public static async Task <FingerprintResult> Authenticate(FingerprintRequestConfig request, OnError errorAction = OnError.Alert)
        {
            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            try
            {
                return(await Thread.UI.Run(async() =>
                {
                    var config = request.ToConfiguration();
                    var result = await CrossFingerprint.Current.AuthenticateAsync(config, request.CancellationToken);

                    return FingerprintResult.From(result);
                }));
            }
            catch (Exception ex)
            {
                await errorAction.Apply(ex, "Failed to access fingerprint: " + ex.Message);

                return(new FingerprintResult
                {
                    Status = FingerprintCheckStatus.Failed,
                    ErrorMessage = ex.Message
                });
            }
        }
Ejemplo n.º 9
0
        /// <summary>Saves a taken video into a local temp folder in the device's cache folder and returns it.</summary>
        public static async Task <FileInfo> TakeVideo(MediaCaptureSettings settings = null, OnError errorAction = OnError.Alert)
        {
            if (!await IsCameraAvailable())
            {
                await errorAction.Apply("No available camera was found on this device.");

                return(null);
            }

            if (!SupportsTakingVideo())
            {
                await errorAction.Apply("Your device does not support recoding video.");

                return(null);
            }

            if (!await Permission.Camera.IsRequestGranted())
            {
                await SuggestLaunchingSettings(errorAction, "Permission was denied to access the camera.");

                return(null);
            }

#if ANDROID
            if (settings?.PurgeCameraRoll == true)
            {
                if (!await Permission.ExternalStorage.IsRequestGranted())
                {
                    await SuggestLaunchingSettings(errorAction, "Permission was denied to access the external storage.");

                    return(null);
                }
            }
#endif

            try
            {
                return(await Thread.UI.Run(() => DoTakeVideo(settings ?? new MediaCaptureSettings())));
            }
            catch (Exception ex)
            {
                await errorAction.Apply(ex, "Failed to capture a video: " + ex.Message);

                return(null);
            }
        }
 public static async Task OnRegisteredSuccess(object token, OnError errorAction = OnError.Toast)
 {
     try { await OnRegisteredSuccess(token); }
     catch (Exception ex)
     {
         await errorAction.Apply(ex, "Failed to consume the token provided by the push notification server.");
     }
 }
Ejemplo n.º 11
0
        /// <summary>Starts tracking the user's DeviceLocation.</summary>
        /// <param name="silently">If set to true, then the tracking will start if DeviceLocation permission is already granted but there will be no user interaction (this can only be used in combination with OnError.Ignore or Throw). If set to false (default) then if necessary, the user will be prompted for granting permission, and in any case the specified error action will apply when there i any problem (GPS not supported or enabled on the device, permission denied, general error, etc.)</param>
        public static async Task <bool> StartTracking(LocationTrackingSettings settings = null, bool silently = false, OnError errorAction = OnError.Alert)
        {
            if (silently && errorAction != OnError.Ignore && errorAction != OnError.Throw)
            {
                throw new Exception("If you want to track the DeviceLocation silently, ErrorAction must be Ignore or Throw.");
            }

            await AskForPermission();

            if (silently && !await Permission.Location.IsGranted())
            {
                await errorAction.Apply("Permission is not already granted to access the current DeviceLocation.");

                return(false);
            }

            if (!await Permission.Location.IsRequestGranted())
            {
                await errorAction.Apply("Permission was not granted to access your current DeviceLocation.");

                return(false);
            }

            if (IsTracking)
            {
                await StopTracking();
            }

            if (settings == null)
            {
                settings = new LocationTrackingSettings();
            }

            try
            {
                await DoStartTracking(settings);

                return(true);
            }
            catch (Exception ex)
            {
                await errorAction.Apply(ex, "Failed to start tracking your DeviceLocation.");

                return(false);
            }
        }
 public static async Task Register(OnError errorAction = OnError.Toast)
 {
     try { await Thread.UI.Run(DoRegister); }
     catch (Exception ex)
     {
         await errorAction.Apply(ex, "Failed to register for push notification.");
     }
 }
 public static async Task UnRegister(object userState = null, OnError errorAction = OnError.Toast)
 {
     try { await Thread.UI.Run(() => DoUnRegister(userState)); }
     catch (Exception ex)
     {
         await errorAction.Apply(ex, "Failed to un-register from push notification.");
     }
 }
Ejemplo n.º 14
0
 public async Task Start(SensorDelay delay = SensorDelay.Game, OnError errorAction = OnError.Toast)
 {
     try
     {
         DoStart(delay);
         IsActive = true;
     }
     catch (Exception ex) { await errorAction.Apply(ex); }
 }
        public static async Task <bool> OnMessageReceived(object message, OnError errorAction = OnError.Toast)
        {
            try { return(await OnMessageReceived(message)); }
            catch (Exception ex)
            {
                await errorAction.Apply(ex, "Failed to process the received message.");

                return(false);
            }
        }
Ejemplo n.º 16
0
        public static async Task <bool> SupportsClipboard(OnError errorAction = OnError.Alert)
        {
            try
            {
                return(SupportsClipboard());
            }
            catch (Exception ex)
            {
                await errorAction.Apply(ex, "Unable to share: ");

                return(false);
            }
        }
Ejemplo n.º 17
0
        public static async Task TurnOn(OnError errorAction = OnError.Toast)
        {
            try
            {
                await SetMode(AndroidCamera.Parameters.FlashModeTorch);

                Camera.StartPreview();
            }
            catch (Exception ex) { await errorAction.Apply(ex); return; }

            // Fix for Nexus 5
            try { Camera.SetPreviewTexture(new SurfaceTexture(0)); }
            catch { /* Ignore. No logging needed. */ }
        }
Ejemplo n.º 18
0
            /// <summary>
            /// Returns the contacts in the device operating system which match the specified search query.
            /// </summary>
            public static async Task <IEnumerable <Contact> > Search(ContactSearchParams searchParams, OnError errorAction = OnError.Alert)
            {
                try
                {
                    if (await Permissions.Check(Permission.Contacts) != PermissionResult.Granted)
                    {
                        if (await Permissions.Request(Permission.Contacts) != PermissionResult.Granted)
                        {
                            await errorAction.Apply("Permission for reading device contacts not granted");

                            return(null);
                        }
                    }

                    return(await DoReadContacts(searchParams));
                }
                catch (Exception ex)
                {
                    await errorAction.Apply(ex, "Failed to read contacts: " + ex.Message);

                    return(null);
                }
            }
Ejemplo n.º 19
0
        static async Task Turn(bool on, OnError errorAction)
        {
            try
            {
                var lamp = await GetLamp();

                if (lamp == null)
                {
                    throw new Exception("Lamp was not found on this device.");
                }

                lamp.IsEnabled = on;
            }
            catch (Exception ex) { await errorAction.Apply(ex); }
        }
Ejemplo n.º 20
0
        public static async Task <bool> SetClipboard(string text, string androidLabel, OnError errorAction = OnError.Alert)
        {
            try
            {
                await DoSetClipboard(text, androidLabel);

                return(true);
            }
            catch (Exception ex)
            {
                await errorAction.Apply(ex, "Attempting to set the clipboard failed: " + ex.Message);

                return(false);
            }
        }
Ejemplo n.º 21
0
        async static Task SuggestLaunchingSettings(OnError errorAction, string error)
        {
            if (errorAction == OnError.Ignore || errorAction == OnError.Throw)
            {
                await errorAction.Apply(error);
            }
            else
            {
                var launchSettings = await Alert.Confirm(error + " Do you want to go to your device settings to enable it?");

                if (launchSettings)
                {
                    await OS.OpenSettings();
                }
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Will launch the external directions application and return whether it was successful.
        /// </summary>
        public static async Task <bool> LaunchDirections(NavigationAddress destination, OnError errorAction = OnError.Toast)
        {
            try
            {
                await AskForPermission();

                await DoLaunchDirections(destination);

                return(true);
            }
            catch (Exception ex)
            {
                await errorAction.Apply(ex, "Launching navigation directions failed");

                return(false);
            }
        }
Ejemplo n.º 23
0
        public static async Task <bool> Share(string text, string title        = null, string url = null, string androidChooserTitle = null,
                                              DeviceSharingOption[] iosExclude = null, OnError errorAction = OnError.Alert)
        {
            try
            {
                await Thread.UI.Run <Task>(() => DoShare(new ShareMessage {
                    Title = title, Text = text, Url = url
                }, androidChooserTitle, iosExclude));

                return(true);
            }
            catch (Exception ex)
            {
                await errorAction.Apply(ex, "Attempting to share failed: " + ex.Message);

                return(false);
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Speaks a specified text using the device's operating system.
        /// </summary>
        public static async Task Speak(string text, Settings settings = null, OnError errorAction = OnError.Toast)
        {
            if (text.IsEmpty()) return;
            settings ??= new Settings();
            settings.Volume = settings.Volume.LimitWithin(0, 1);

            SpeechInProgress?.TrySetResult(false);

            SpeechInProgress = new TaskCompletionSource<bool>();

            try
            {
                await DoSpeak(text, settings);
                await SpeechInProgress.Task;
            }
            catch (Exception ex)
            {
                await errorAction.Apply(ex, "Failed to run Text to Speech.");
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Saves a specified image file to the device's camera roll.
        /// </summary>
        public static async Task <bool> SaveToAlbum(FileInfo file, OnError errorAction = OnError.Alert)
        {
            try
            {
                if (!await Permission.Albums.IsRequestGranted())
                {
                    throw new Exception("Permission to access the device albums (gallery) was denied.");
                }

                await Thread.UI.Run(() => DoSaveToAlbum(file)).ConfigureAwait(false);

                return(true);
            }
            catch (Exception ex)
            {
                await errorAction.Apply(ex, "Failed to save a file to album: " + ex.Message);

                return(false);
            }
        }
Ejemplo n.º 26
0
        public static Task StartRecording(OnError errorAction = OnError.Toast)
        {
            try
            {
                if (Recording?.Exists() == true)
                {
                    lock (Recording.GetSyncLock())
                        Recording.Delete();
                }

                var newFile = $"Myfile{DateTime.UtcNow.ToString("yyyyMMddHHmmss")}.wav";
                Recording = IO.CreateTempDirectory().GetFile(newFile);
                lock (Recording.GetSyncLock())
                    Recording.Delete();

                CreateRecorder();
                Recorder.Start();
                return(Task.CompletedTask);
            }
            catch (Exception ex) { return(errorAction.Apply(ex)); }
        }
Ejemplo n.º 27
0
        public static async Task Run(TimeSpan duration, OnError errorAction = OnError.Toast)
        {
            try
            {
                if (!await Device.Permission.Vibration.IsRequestGranted())
                {
                    throw new Exception("Permission to vibrate was denied.");
                }

                if (!IsAvailable())
                {
                    throw new Exception("Vibration is not available on this device.");
                }

                await DoRun((int)duration.TotalMilliseconds);
            }
            catch (Exception ex)
            {
                await errorAction.Apply(ex, "Vibration request failed.");
            }
        }
Ejemplo n.º 28
0
            public static async Task <bool> Start(Action <string, bool> listener, OnError errorAction = OnError.Alert)
            {
                try { await Stop(); } catch { /* No logging is needed. */ }

                try
                {
                    if (!await Permission.Speech.IsRequestGranted())
                    {
                        throw new Exception("Request was denied to access Speech Recognition.");
                    }

                    await Thread.UI.Run(DoStart);

                    Listeners += listener;
                    return(true);
                }
                catch (Exception ex)
                {
                    await errorAction.Apply(ex);

                    return(false);
                }
            }
Ejemplo n.º 29
0
        public static async Task StartRecording(OnError errorAction = OnError.Toast)
        {
            try
            {
                await StopRecording();

                if (Recording?.Exists() == true)
                {
                    lock (Recording.GetSyncLock())
                        Recording.Delete();
                }

                var newFile = $"Myfile{DateTime.UtcNow.ToString("yyyyMMddHHmmss")}.wav";
                Recording = Device.IO.CreateTempDirectory().GetFile(newFile);
                lock (Recording.GetSyncLock())
                    Recording.Delete();

                CreateRecorder();

                Recorder.Record();
            }
            catch (Exception ex) { await errorAction.Apply(ex); }
        }
Ejemplo n.º 30
0
 public static async Task StartRecording(OnError errorAction = OnError.Toast)
 {
     try { await Thread.Pool.Run(() => DoStartRecording()); }
     catch (Exception ex) { await errorAction.Apply(ex); }
 }