Permissions Plugin for Xamarin (Simplifying Runtime Permissions)

2»

Posts

  • pauldpauld USMember ✭✭

    @SuatKorkmaz said:
    In MainActivity.cs:

            protected override void OnCreate(Bundle bundle)
            {
                base.OnCreate(bundle);
                CrossCurrentActivity.Current.Activity = this;
                global::Xamarin.Forms.Forms.Init(this, bundle);
                LoadApplication(new App());
            }
    

    Thank you! I'd added this plugin a while ago but couldn't get it to do anything at all. This fixed it.

  • DamienDoumerDamienDoumer USMember
    edited July 2017

    Hey everyone, I cant find a solution to this issue anywhere,
    On android, I Requesting permissions Doesnot function I use James' Example:
    await Application.Current?.MainPage?.DisplayAlert("Need location", "Gunna need that location", "OK");

    and also I always have location permissions to granted no matter what,
    but when I switch off my locations on my device : Galaxy s4 with Kitkat.
    I get the permission request task canceled all the time, I don't know what to do, anyone please help.

    var resultrs = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Location });

    I use James' example in my code.

  • Robert_VdVRobert_VdV USMember ✭✭
    edited October 2017

    Hey,

    While using this plugin, but also without using this plugin and using the routine described here, my Xamarin Android app is experiencing some sort of Window Leak while the Permission Request Dialog is shown. When I click a button, which method needs permission to write to the external storrage, the Permission Request Dialog pops up and in the background my app disappears and the Home Screen is shown - behind the Permission Request Dialog.

    When I click Allow, the setting is saved (this can be checked at Settings, Apps, [MyApp], Permissions ), but the app won't come back up. When reopening the app and call the method that is checking for permission again, it continues what it needs to do; writing to the external storage.

    I've already made sure the Dialog with a spinner during the async delegate is dismissed before the Permission Request is addressed and commented out a Toast to prevent it from interfering. Is it the Permission Request Dialog itself that is causing the Window Leak?

    Phone: Samsung Galaxy A3 (2017)
    Android version: 6.0.1

    My Activity starts like this:

    using Android;
    using Android.App;
    using Android.Content;
    using Android.OS;
    using Android.Runtime;
    using Android.Support.V4.App;
    using Android.Views;
    using Android.Widget;
    using MailKit.Net.Smtp;
    using MimeKit;
    using Plugin.Permissions;
    using Plugin.Permissions.Abstractions;
    using System;
    using System.IO;
    using System.Threading.Tasks;
    
    namespace MyApp
    {
        [Activity(Label = "Settings", ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait, NoHistory = true)]
        class SettingsActivity : Activity, ActivityCompat.IOnRequestPermissionsResultCallback
        {
    

    I've got the override:

    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    

    This is the delegate that handles a button click event

    searchUpdateAppBtn.Click += async delegate
    {
        // Show Spinner
        ShowSpinner();
    
        var updateSearch = await SearchForUpdate();
    
        if (updateSearch.result)
        {
            if (updateSearch.project.PublishUpdate)
            {
                updateUrl = updateSearch.project.LatestApkUrl;
                md5 = updateSearch.project.ApkMd5;
    
                searchUpdateAppBtn.Enabled = false;
    
                try
                { // LOG IS FROM THIS POINT ON
    
            // Dismiss Spinner
                    DismissSpinner();
    
                    var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
                    if (status != PermissionStatus.Granted)
                    {
                        if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Storage))
                        {
                            //Toast.MakeText(this, "Toestemming is nodig voor het downloaden van de update.", ToastLength.Short).Show();
                        }
    
                        var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Storage);
                        //Best practice to always check that the key exists
                        if (results.ContainsKey(Permission.Storage))
                            status = results[Permission.Storage];
                    }
    
                    if (status == PermissionStatus.Granted)
                    {
                        await DownloadUpdate(updateUrl, md5);
                    }
                    else if (status != PermissionStatus.Unknown)
                    {
                        Toast.MakeText(this, "Toestemming verkrijgen is mislukt. Probeer het opnieuw.", ToastLength.Long).Show();
                    }
                }
                catch (Exception ex)
                {
                    Toast.MakeText(this, $"Er is een fout opgetreden: {ex.Message}", ToastLength.Long).Show();
                }
            }
            else
            {
                // Show Result
                Toast.MakeText(this, $"Je hebt al de laatste versie van de app!", ToastLength.Short).Show();
            }
        }
        else
        {
            // Show Result
            Toast.MakeText(this, $"Er is geen update gevonden: {updateSearch.resultMessage}", ToastLength.Long).Show();
        }
    
        // Dismiss Spinner
        DismissSpinner();
    };
    

    This is the log from where the Try\Catch starts:

    10-11 19:15:40.511 D/ViewRootImpl(16616): #3 mView = null
    10-11 19:15:40.531 D/Mono    (16616): Assembly Ref addref Plugin.Permissions[0xebcfc3a0] -> Mono.Android[0xebcfcfa0]: 23
    10-11 19:15:40.531 D/Mono    (16616): Assembly Ref addref Plugin.Permissions[0xebcfc3a0] -> Plugin.CurrentActivity[0xebcfc160]: 3
    10-11 19:15:40.531 D/Mono    (16616): Assembly Ref addref Plugin.Permissions[0xebcfc3a0] -> Xamarin.Android.Support.Compat[0xebcfc7c0]: 3
    10-11 19:15:40.541 D/Mono    (16616): Assembly Ref addref Plugin.Permissions[0xebcfc3a0] -> System.Core[0xf37edba0]: 9
    10-11 19:15:40.551 D/Mono    (16616): Image addref System.Xml[0xd59990a0] -> System.Xml.dll[0xd5986e00]: 2
    10-11 19:15:40.551 D/Mono    (16616): Prepared to set up assembly 'System.Xml' (System.Xml.dll)
    10-11 19:15:40.551 D/Mono    (16616): Assembly System.Xml[0xd59990a0] added to domain RootDomain, ref_count=1
    10-11 19:15:40.551 D/Mono    (16616): AOT: image 'System.Xml.dll.so' not found: dlopen failed: library "/data/app/RMB.StockTaker-1/lib/arm/libaot-System.Xml.dll.so" not found
    10-11 19:15:40.551 D/Mono    (16616): AOT: image '/usr/local/lib/mono/aot-cache/arm/System.Xml.dll.so' not found: dlopen failed: library "/data/app/RMB.StockTaker-1/lib/arm/libaot-System.Xml.dll.so" not found
    10-11 19:15:40.551 D/Mono    (16616): Config attempting to parse: 'System.Xml.dll.config'.
    10-11 19:15:40.551 D/Mono    (16616): Config attempting to parse: '/usr/local/etc/mono/assemblies/System.Xml/System.Xml.config'.
    10-11 19:15:40.551 D/Mono    (16616): Assembly Ref addref Mono.Android[0xebcfcfa0] -> System.Xml[0xd59990a0]: 2
    10-11 19:15:40.561 D/Mono    (16616): Assembly Ref addref System.Xml[0xd59990a0] -> mscorlib[0xebcfb9e0]: 48
    Loaded assembly: System.Xml.dll [External]
    10-11 19:15:40.591 D/Mono    (16616): DllImport searching in: '__Internal' ('(null)').
    10-11 19:15:40.591 D/Mono    (16616): Searching for 'java_interop_jnienv_get_field_id'.
    10-11 19:15:40.591 D/Mono    (16616): Probing 'java_interop_jnienv_get_field_id'.
    10-11 19:15:40.591 D/Mono    (16616): Found as 'java_interop_jnienv_get_field_id'.
    10-11 19:15:40.591 D/Mono    (16616): DllImport searching in: '__Internal' ('(null)').
    10-11 19:15:40.591 D/Mono    (16616): Searching for 'java_interop_jnienv_get_object_field'.
    10-11 19:15:40.591 D/Mono    (16616): Probing 'java_interop_jnienv_get_object_field'.
    10-11 19:15:40.591 D/Mono    (16616): Found as 'java_interop_jnienv_get_object_field'.
    10-11 19:15:40.611 D/Mono    (16616): DllImport searching in: '__Internal' ('(null)').
    10-11 19:15:40.611 D/Mono    (16616): Searching for 'java_interop_jnienv_get_object_array_element'.
    10-11 19:15:40.611 D/Mono    (16616): Probing 'java_interop_jnienv_get_object_array_element'.
    10-11 19:15:40.611 D/Mono    (16616): Found as 'java_interop_jnienv_get_object_array_element'.
    10-11 19:15:40.631 D/Mono    (16616): DllImport searching in: '__Internal' ('(null)').
    10-11 19:15:40.631 D/Mono    (16616): Searching for 'java_interop_jnienv_call_static_boolean_method_a'.
    10-11 19:15:40.631 D/Mono    (16616): Probing 'java_interop_jnienv_call_static_boolean_method_a'.
    10-11 19:15:40.631 D/Mono    (16616): Found as 'java_interop_jnienv_call_static_boolean_method_a'.
    10-11 19:15:40.651 D/Mono    (16616): DllImport searching in: '__Internal' ('(null)').
    10-11 19:15:40.651 D/Mono    (16616): Searching for 'java_interop_jnienv_new_object_array'.
    10-11 19:15:40.651 D/Mono    (16616): Probing 'java_interop_jnienv_new_object_array'.
    10-11 19:15:40.651 D/Mono    (16616): Found as 'java_interop_jnienv_new_object_array'.
    10-11 19:15:40.661 D/Mono    (16616): DllImport searching in: '__Internal' ('(null)').
    10-11 19:15:40.661 D/Mono    (16616): Searching for 'java_interop_jnienv_set_object_array_element'.
    10-11 19:15:40.661 D/Mono    (16616): Probing 'java_interop_jnienv_set_object_array_element'.
    10-11 19:15:40.661 D/Mono    (16616): Found as 'java_interop_jnienv_set_object_array_element'.
    10-11 19:15:40.681 I/Choreographer(16616): Skipped 390 frames!  The application may be doing too much work on its main thread.
    10-11 19:15:40.681 E/ViewRootImpl(16616): sendUserActionEvent() mView == null
    10-11 19:15:41.061 D/ViewRootImpl(16616): #3 mView = null
    
  • Robert_VdVRobert_VdV USMember ✭✭

    Hey,

    Manually requesting a software update, updated the phone to Android version 7.0. This solved the issue, for at least phones with version 7.0. So I don't think it is related to requesting permissions. So if a moderator can please remove my posts (this one and the one above) to keep the topic clean, that would be great!

    Thanks

  • vladpredovicvladpredovic USMember ✭✭
      Quick implementation to check multiple permissions  
    
    
        private async Task<bool> GetPermissions()
            {
                bool permissionsGranted = false;
                try
                {
                    var permissionsList = new List<Permission>()
                    {
                        Permission.Location,
                        Permission.LocationAlways,
                        Permission.LocationWhenInUse,
                        Permission.Storage,
                        Permission.Phone
                    };
    
                    foreach(var permission in permissionsList)
                    {
                        var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
    
                        if (status != PermissionStatus.Granted)
                        {
                            if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(permission))
                            {
                                await App.Current.MainPage.DisplayAlert("Need a permission", $"Required: {permission.ToString()}", "OK");
                            }
    
                            var results = await CrossPermissions.Current.RequestPermissionsAsync(permission);
                            //Best practice to always check that the key exists
                            if (results.ContainsKey(permission))
                                status = results[permission];
                            if (status == PermissionStatus.Granted || status == PermissionStatus.Unknown)
                            {
                                permissionsGranted =  true;
                            }
                            else
                            {
                                await App.Current.MainPage.DisplayAlert("Location Denied", "Can not continue, try again.", "OK");
                                permissionsGranted = false;
                                break;
                            }
                        }
                    }
    
                }
                catch (System.Exception ex)
                {
                    await App.Current.MainPage.DisplayAlert("Error", "Error: " + ex.Message, "Ok");
                    logger.DebugLogError("Fatal Error on permissions: " + ex.Message);
                }
                return permissionsGranted;
            }``````````
    
  • @JamesMontemagno said:
    What device and OS is it running?

    I am facing the same issue. Device Moto G5

  • SuatKorkmazSuatKorkmaz USMember ✭✭✭

    @pauld said:

    @SuatKorkmaz said:
    In MainActivity.cs:

            protected override void OnCreate(Bundle bundle)
            {
                base.OnCreate(bundle);
                CrossCurrentActivity.Current.Activity = this;
                global::Xamarin.Forms.Forms.Init(this, bundle);
                LoadApplication(new App());
            }
    

    Thank you! I'd added this plugin a while ago but couldn't get it to do anything at all. This fixed it.

    You're welcome.

  • VladisVladis USMember ✭✭

    @vladpredovic said:
    Quick implementation to check multiple permissions

      private async Task<bool> GetPermissions()
            {
                bool permissionsGranted = false;
                try
                {
                    var permissionsList = new List<Permission>()
                    {
                        Permission.Location,
                        Permission.LocationAlways,
                        Permission.LocationWhenInUse,
                        Permission.Storage,
                        Permission.Phone
                    };
    
                    foreach(var permission in permissionsList)
                    {
                        var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
    
                        if (status != PermissionStatus.Granted)
                        {
                            if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(permission))
                            {
                                await App.Current.MainPage.DisplayAlert("Need a permission", $"Required: {permission.ToString()}", "OK");
                            }
    
                            var results = await CrossPermissions.Current.RequestPermissionsAsync(permission);
                            //Best practice to always check that the key exists
                            if (results.ContainsKey(permission))
                                status = results[permission];
                            if (status == PermissionStatus.Granted || status == PermissionStatus.Unknown)
                            {
                                permissionsGranted =  true;
                            }
                            else
                            {
                                await App.Current.MainPage.DisplayAlert("Location Denied", "Can not continue, try again.", "OK");
                                permissionsGranted = false;
                                break;
                            }
                        }
                    }
                   
                }
                catch (System.Exception ex)
                {
                    await App.Current.MainPage.DisplayAlert("Error", "Error: " + ex.Message, "Ok");
                    logger.DebugLogError("Fatal Error on permissions: " + ex.Message);
                }
                return permissionsGranted;
            }``````````
    

    This was wrong due to an exception being cause by removing elements while looping.

    This is a better version which will run straight out of the box (feel free to remove the logging/try/catch if you feel).

       public static async Task<bool> GetPermissions()
        {
            bool permissionsGranted = true;
    
            var permissionsStartList = new List<Permission>()
            {
                Permission.Location,
                Permission.LocationAlways,
                Permission.LocationWhenInUse,
                Permission.Storage,
                Permission.Phone
            };
            var permissionsNeededList = new List<Permission>();
            try
            {
                foreach (var permission in permissionsStartList)
                {
                    var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
                    if (status != PermissionStatus.Granted)
                    {
                        permissionsNeededList.Add(permission);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHandler.LogError($"+ {ex.Message}", new Dictionary<string, string> {
                { "Inner Exception" , ex.InnerException?.Message },
                { "stack Trace" , ex.InnerException?.StackTrace },
                { "date and time" , DateTimeOffset.Now.ToString("dddd, MMM dd yyyy HH:mm:ss zzz") },
                }); ;
            }
    
            var results = await CrossPermissions.Current.RequestPermissionsAsync(permissionsNeededList.ToArray());
    
            try
            {
                foreach(var permission in permissionsNeededList)
                {
                    var status = PermissionStatus.Unknown;
                    //Best practice to always check that the key exists
                    if (results.ContainsKey(permission))
                        status = results[permission];
                    if (status == PermissionStatus.Granted || status == PermissionStatus.Unknown)
                    {
                        permissionsGranted = true;
                    }
                    else
                    {
                        permissionsGranted = false;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHandler.LogError($"+ {ex.Message}", new Dictionary<string, string> {
                { "Inner Exception" , ex.InnerException?.Message },
                { "stack Trace" , ex.InnerException?.StackTrace },
                { "date and time" , DateTimeOffset.Now.ToString("dddd, MMM dd yyyy HH:mm:ss zzz") },
                });
            }
        return permissionsGranted;
        }
    
    }
    
  • ShrutiGoyal.5169ShrutiGoyal.5169 USMember ✭✭
    edited March 23

    @JamesMontemagno @hvaughan

    Awesome plugin. Just installed it and wrote some code following your example above. I am having an issue though when running the code on a Nexus 7 API 23 emulator and requesting Phone permissions, though I wonder if I am doing it wrong. When the app is first installed to the emulator it looks like all of the permissions I requested in the manifest are automatically switched to granted, which is fine, and when I run CheckPermissionStatus() it correctly returns PermissionStatus.Granted. The issue happens when I try and go into the emulator's settings and switch the 'Phone' permission off, whether I first kill the app or whether I switch it off while the app is running, and then I run the CheckPermissionStatus() again. The method still returns PermissionStatus.Granted. I would post a bug report in GitHub but I am currently not able to login to my GitHub account as I am waiting for a new phone in the mail and lost my damned recovery code. Code below: try { PermissionStatus status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission); if(status != PermissionStatus.Granted) { //It has not been granted so lets ask if(await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(permission)) { await App.AppNavPage.DisplayAlert(permission + " Permission Request", "In order for the app to " + GetPermissionVerbString(permission) + ", permission must first be granted.", "OK"); } Dictionary results = await CrossPermissions.Current.RequestPermissionsAsync(permission); status = results[permission]; } return status; } catch(Exception ex) { System.Diagnostics.Debug.WriteLine("\nIn App.Helpers.NetworkHelper.CheckRequestPermissionAsync() - Exception attempting to check or request permission to Permission.{0}:\n{1}\n", permission, ex); return PermissionStatus.Unknown; }

    I am getting same issue with latest library version 2.2.1. and I'm working on Moto G3 API 23

  • shubham1shubham1 Member ✭✭✭

    @vladpredovic said:
    Quick implementation to check multiple permissions

      private async Task<bool> GetPermissions()
            {
                bool permissionsGranted = false;
                try
                {
                    var permissionsList = new List<Permission>()
                    {
                        Permission.Location,
                        Permission.LocationAlways,
                        Permission.LocationWhenInUse,
                        Permission.Storage,
                        Permission.Phone
                    };
    
                    foreach(var permission in permissionsList)
                    {
                        var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
    
                        if (status != PermissionStatus.Granted)
                        {
                            if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(permission))
                            {
                                await App.Current.MainPage.DisplayAlert("Need a permission", $"Required: {permission.ToString()}", "OK");
                            }
    
                            var results = await CrossPermissions.Current.RequestPermissionsAsync(permission);
                            //Best practice to always check that the key exists
                            if (results.ContainsKey(permission))
                                status = results[permission];
                            if (status == PermissionStatus.Granted || status == PermissionStatus.Unknown)
                            {
                                permissionsGranted =  true;
                            }
                            else
                            {
                                await App.Current.MainPage.DisplayAlert("Location Denied", "Can not continue, try again.", "OK");
                                permissionsGranted = false;
                                break;
                            }
                        }
                    }
                   
                }
                catch (System.Exception ex)
                {
                    await App.Current.MainPage.DisplayAlert("Error", "Error: " + ex.Message, "Ok");
                    logger.DebugLogError("Fatal Error on permissions: " + ex.Message);
                }
                return permissionsGranted;
            }``````````
    

    Hey, while implementing your code I am getting error in

    Permission.Location

  • shubham1shubham1 Member ✭✭✭

    @Vladis said:

    @vladpredovic said:
    Quick implementation to check multiple permissions

        private async Task<bool> GetPermissions()
            {
                bool permissionsGranted = false;
                try
                {
                    var permissionsList = new List<Permission>()
                    {
                        Permission.Location,
                        Permission.LocationAlways,
                        Permission.LocationWhenInUse,
                        Permission.Storage,
                        Permission.Phone
                    };
    
                    foreach(var permission in permissionsList)
                    {
                        var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
    
                        if (status != PermissionStatus.Granted)
                        {
                            if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(permission))
                            {
                                await App.Current.MainPage.DisplayAlert("Need a permission", $"Required: {permission.ToString()}", "OK");
                            }
    
                            var results = await CrossPermissions.Current.RequestPermissionsAsync(permission);
                            //Best practice to always check that the key exists
                            if (results.ContainsKey(permission))
                                status = results[permission];
                            if (status == PermissionStatus.Granted || status == PermissionStatus.Unknown)
                            {
                                permissionsGranted =  true;
                            }
                            else
                            {
                                await App.Current.MainPage.DisplayAlert("Location Denied", "Can not continue, try again.", "OK");
                                permissionsGranted = false;
                                break;
                            }
                        }
                    }
                   
                }
                catch (System.Exception ex)
                {
                    await App.Current.MainPage.DisplayAlert("Error", "Error: " + ex.Message, "Ok");
                    logger.DebugLogError("Fatal Error on permissions: " + ex.Message);
                }
                return permissionsGranted;
            }``````````
    

    This was wrong due to an exception being cause by removing elements while looping.

    This is a better version which will run straight out of the box (feel free to remove the logging/try/catch if you feel).

       public static async Task<bool> GetPermissions()
        {
            bool permissionsGranted = true;
    
            var permissionsStartList = new List<Permission>()
            {
                Permission.Location,
                Permission.LocationAlways,
                Permission.LocationWhenInUse,
                Permission.Storage,
                Permission.Phone
            };
            var permissionsNeededList = new List<Permission>();
            try
            {
                foreach (var permission in permissionsStartList)
                {
                    var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
                    if (status != PermissionStatus.Granted)
                    {
                        permissionsNeededList.Add(permission);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHandler.LogError($"+ {ex.Message}", new Dictionary<string, string> {
                { "Inner Exception" , ex.InnerException?.Message },
                { "stack Trace" , ex.InnerException?.StackTrace },
                { "date and time" , DateTimeOffset.Now.ToString("dddd, MMM dd yyyy HH:mm:ss zzz") },
                }); ;
            }
    
            var results = await CrossPermissions.Current.RequestPermissionsAsync(permissionsNeededList.ToArray());
    
            try
            {
                foreach(var permission in permissionsNeededList)
                {
                    var status = PermissionStatus.Unknown;
                    //Best practice to always check that the key exists
                    if (results.ContainsKey(permission))
                        status = results[permission];
                    if (status == PermissionStatus.Granted || status == PermissionStatus.Unknown)
                    {
                        permissionsGranted = true;
                    }
                    else
                    {
                        permissionsGranted = false;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHandler.LogError($"+ {ex.Message}", new Dictionary<string, string> {
                { "Inner Exception" , ex.InnerException?.Message },
                { "stack Trace" , ex.InnerException?.StackTrace },
                { "date and time" , DateTimeOffset.Now.ToString("dddd, MMM dd yyyy HH:mm:ss zzz") },
                });
            }
        return permissionsGranted;
        }
    
    }
    

    Hey, while implementing your code I am getting error in

    Permission.Location

  • netosilva_xonetosilva_xo Member
    edited May 14

    I'm getting this error "System.MissingMethodException: Method 'Plugin.Permissions.CrossPermissions.get_Current' not found.". Can anyone help me?

    EDIT
    Solved it cleaning my project, deleting bin and obj folders.

  • _Jai_Jai USMember ✭✭

    @Shubhuuu said:

    @vladpredovic said:
    Quick implementation to check multiple permissions

        private async Task<bool> GetPermissions()
            {
                bool permissionsGranted = false;
                try
                {
                    var permissionsList = new List<Permission>()
                    {
                        Permission.Location,
                        Permission.LocationAlways,
                        Permission.LocationWhenInUse,
                        Permission.Storage,
                        Permission.Phone
                    };
    
                    foreach(var permission in permissionsList)
                    {
                        var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
    
                        if (status != PermissionStatus.Granted)
                        {
                            if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(permission))
                            {
                                await App.Current.MainPage.DisplayAlert("Need a permission", $"Required: {permission.ToString()}", "OK");
                            }
    
                            var results = await CrossPermissions.Current.RequestPermissionsAsync(permission);
                            //Best practice to always check that the key exists
                            if (results.ContainsKey(permission))
                                status = results[permission];
                            if (status == PermissionStatus.Granted || status == PermissionStatus.Unknown)
                            {
                                permissionsGranted =  true;
                            }
                            else
                            {
                                await App.Current.MainPage.DisplayAlert("Location Denied", "Can not continue, try again.", "OK");
                                permissionsGranted = false;
                                break;
                            }
                        }
                    }
                   
                }
                catch (System.Exception ex)
                {
                    await App.Current.MainPage.DisplayAlert("Error", "Error: " + ex.Message, "Ok");
                    logger.DebugLogError("Fatal Error on permissions: " + ex.Message);
                }
                return permissionsGranted;
            }``````````
    

    Hey, while implementing your code I am getting error in

    Permission.Location

    When you install this plugin it will also install a file called "MainApplication.cs" into your Android app and that needs to be there.If Not You add It. I am adding code insode the MainApplication.cs file here

    using System;
    using Android.App;
    using Android.OS;
    using Android.Runtime;
    using Plugin.CurrentActivity;

    namespace AppName.Droid
    {
    //You can specify additional application information in this attribute
    [Application]
    public class MainApplication : Application, Application.IActivityLifecycleCallbacks
    {
    public MainApplication(IntPtr handle, JniHandleOwnership transer)
    : base(handle, transer)
    {
    }

        public override void OnCreate()
        {
            base.OnCreate();
            RegisterActivityLifecycleCallbacks(this);
            //A great place to initialize Xamarin.Insights and Dependency Services!
        }
    
        public override void OnTerminate()
        {
            base.OnTerminate();
            UnregisterActivityLifecycleCallbacks(this);
        }
    
        public void OnActivityCreated(Activity activity, Bundle savedInstanceState)
        {
            CrossCurrentActivity.Current.Activity = activity;
        }
    
        public void OnActivityDestroyed(Activity activity)
        {
        }
    
        public void OnActivityPaused(Activity activity)
        {
        }
    
        public void OnActivityResumed(Activity activity)
        {
            CrossCurrentActivity.Current.Activity = activity;
        }
    
        public void OnActivitySaveInstanceState(Activity activity, Bundle outState)
        {
        }
    
        public void OnActivityStarted(Activity activity)
        {
            CrossCurrentActivity.Current.Activity = activity;
        }
    
        public void OnActivityStopped(Activity activity)
        {
        }
    }
    

    }

  • shubham1shubham1 Member ✭✭✭
    edited May 29

    @_Jai said:

    @Shubhuuu said:

    @vladpredovic said:
    Quick implementation to check multiple permissions

      private async Task<bool> GetPermissions()
            {
                bool permissionsGranted = false;
                try
                {
                    var permissionsList = new List<Permission>()
                    {
                        Permission.Location,
                        Permission.LocationAlways,
                        Permission.LocationWhenInUse,
                        Permission.Storage,
                        Permission.Phone
                    };
    
                    foreach(var permission in permissionsList)
                    {
                        var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
    
                        if (status != PermissionStatus.Granted)
                        {
                            if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(permission))
                            {
                                await App.Current.MainPage.DisplayAlert("Need a permission", $"Required: {permission.ToString()}", "OK");
                            }
    
                            var results = await CrossPermissions.Current.RequestPermissionsAsync(permission);
                            //Best practice to always check that the key exists
                            if (results.ContainsKey(permission))
                                status = results[permission];
                            if (status == PermissionStatus.Granted || status == PermissionStatus.Unknown)
                            {
                                permissionsGranted =  true;
                            }
                            else
                            {
                                await App.Current.MainPage.DisplayAlert("Location Denied", "Can not continue, try again.", "OK");
                                permissionsGranted = false;
                                break;
                            }
                        }
                    }
                   
                }
                catch (System.Exception ex)
                {
                    await App.Current.MainPage.DisplayAlert("Error", "Error: " + ex.Message, "Ok");
                    logger.DebugLogError("Fatal Error on permissions: " + ex.Message);
                }
                return permissionsGranted;
            }``````````
    

    Hey, while implementing your code I am getting error in

    Permission.Location

    When you install this plugin it will also install a file called "MainApplication.cs" into your Android app and that needs to be there.If Not You add It. I am adding code insode the MainApplication.cs file here

    using System;
    using Android.App;
    using Android.OS;
    using Android.Runtime;
    using Plugin.CurrentActivity;

    namespace AppName.Droid
    {
    //You can specify additional application information in this attribute
    [Application]
    public class MainApplication : Application, Application.IActivityLifecycleCallbacks
    {
    public MainApplication(IntPtr handle, JniHandleOwnership transer)
    : base(handle, transer)
    {
    }

        public override void OnCreate()
        {
            base.OnCreate();
            RegisterActivityLifecycleCallbacks(this);
            //A great place to initialize Xamarin.Insights and Dependency Services!
        }
    
        public override void OnTerminate()
        {
            base.OnTerminate();
            UnregisterActivityLifecycleCallbacks(this);
        }
    
        public void OnActivityCreated(Activity activity, Bundle savedInstanceState)
        {
            CrossCurrentActivity.Current.Activity = activity;
        }
    
        public void OnActivityDestroyed(Activity activity)
        {
        }
    
        public void OnActivityPaused(Activity activity)
        {
        }
    
        public void OnActivityResumed(Activity activity)
        {
            CrossCurrentActivity.Current.Activity = activity;
        }
    
        public void OnActivitySaveInstanceState(Activity activity, Bundle outState)
        {
        }
    
        public void OnActivityStarted(Activity activity)
        {
            CrossCurrentActivity.Current.Activity = activity;
        }
    
        public void OnActivityStopped(Activity activity)
        {
        }
    }
    

    }

    Thank you so much for your response. But I have done that earlier.

  • hkiddhkidd Member ✭✭

    Hi - is there a way to use the Permissions Plugin to cause a dialog box to pop up to grant user permission to the camera? I would like to have a box appear with Deny and Allow rather than navigate the user out of the app and to Settings. Is this possible with the Permissions Plugin or do I need to use an alternative option?

  • TimStevensonTimStevenson USMember ✭✭
    edited June 26

    I'm having a problem with RequestPermissionAsync() when trying to get a location permission for iOS 11.4. I have the Android side working just fine. This line of code executes and nothing ever returns. No errors or anything:

    var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location);

    These are the Permissions I have set in my Info.plist:

      <key>NSLocationAlwaysUsageDescription</key>
      <string>Can we use your location?</string>
      <key>NSLocationWhenInUseUsageDescription</key>
      <string>We are using your location.</string>
      <key>NSCalendarsUsageDescription</key>
      <string>Needs Calendar Permission</string>
      <key>NSBluetoothPeripheralUsageDescription</key>
      <string>Needs Bluetooth Peripheral Permission</string>
    

    Is it timing out? Am I missing a configuration or something? There is nothing to be configured in Main.cs or AppDelegate.cs, correct?

    Edit:

    I should probably add that this line in iOS returns PermissionStatus.Unknown also:
    var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);

  • 15mgm1515mgm15 USMember ✭✭✭✭

    @TimStevenson Did you found a solution for this?

  • TimStevensonTimStevenson USMember ✭✭

    @15mgm15 said:
    @TimStevenson Did you found a solution for this?

    Not yet. I haven't had a chance to work on it today. Still looking for suggestions.

  • 15mgm1515mgm15 USMember ✭✭✭✭
    edited June 27

    @JamesMontemagno Using iOS 11.4 I have:

    var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.MediaLibrary});

    and boom! The applications is crashing with this log:

    2018-06-27 17:18:21.948 SchedulingTool.iOS[69460:2965142] critical:     0   SchedulingTool.iOS                  0x0000000109f1f5a4 mono_handle_native_crash + 244
    2018-06-27 17:18:21.949 SchedulingTool.iOS[69460:2965142] critical:     1   libsystem_platform.dylib            0x000000011b345f5a _sigtramp + 26
    2018-06-27 17:18:21.949 SchedulingTool.iOS[69460:2965142] critical:     2   ???                                 0x000000010a9e5a48 0x0 + 4473117256
    2018-06-27 17:18:21.950 SchedulingTool.iOS[69460:2965142] critical:     3   libsystem_kernel.dylib              0x000000011b31a2fc fcntl + 0
    2018-06-27 17:18:21.951 SchedulingTool.iOS[69460:2965142] critical:     4   TCC                                 0x000000011f304bb7 __TCCAccessRequest_block_invoke.85 + 0
    2018-06-27 17:18:21.951 SchedulingTool.iOS[69460:2965142] critical:     5   TCC                                 0x000000011f304b0a __CRASHING_DUE_TO_PRIVACY_VIOLATION__ + 0
    2018-06-27 17:18:21.952 SchedulingTool.iOS[69460:2965142] critical:     6   TCC                                 0x000000011f308259 __tccd_send_block_invoke + 265
    2018-06-27 17:18:21.953 SchedulingTool.iOS[69460:2965142] critical:     7   libxpc.dylib                        0x000000011b2653b2 _xpc_connection_reply_callout + 36
    2018-06-27 17:18:21.954 SchedulingTool.iOS[69460:2965142] critical:     8   libxpc.dylib                        0x000000011b25a6e0 _xpc_connection_call_reply_async + 82
    2018-06-27 17:18:21.954 SchedulingTool.iOS[69460:2965142] critical:     9   libdispatch.dylib                   0x000000011ae3476b _dispatch_client_callout3 + 8
    2018-06-27 17:18:21.955 SchedulingTool.iOS[69460:2965142] critical:     10  libdispatch.dylib                   0x000000011ae493ee _dispatch_mach_msg_async_reply_invoke + 364
    2018-06-27 17:18:21.955 SchedulingTool.iOS[69460:2965142] critical:     11  libdispatch.dylib                   0x000000011ae390fa _dispatch_queue_override_invoke + 477
    2018-06-27 17:18:21.956 SchedulingTool.iOS[69460:2965142] critical:     12  libdispatch.dylib                   0x000000011ae3ec88 _dispatch_root_queue_drain + 473
    2018-06-27 17:18:21.956 SchedulingTool.iOS[69460:2965142] critical:     13  libdispatch.dylib                   0x000000011ae3ea51 _dispatch_worker_thread3 + 119
    2018-06-27 17:18:21.956 SchedulingTool.iOS[69460:2965142] critical:     14  libsystem_pthread.dylib             0x000000011b357169 _pthread_wqthread + 1387
    2018-06-27 17:18:21.957 SchedulingTool.iOS[69460:2965142] critical:     15  libsystem_pthread.dylib             0x000000011b356be9 start_wqthread + 13
    2018-06-27 17:18:21.957 SchedulingTool.iOS[69460:2965142] critical: 
    =================================================================
    Got a SIGABRT while executing native code. This usually indicates
    a fatal error in the mono runtime or one of the native libraries 
    used by your application.
    =================================================================
    
  • 15mgm1515mgm15 USMember ✭✭✭✭

    Silly me... I was using Permission.MediaLibrary in stead of Permission.Photos <- This was causing the crash.

  • SimonJeffsSimonJeffs USMember ✭✭

    Its not quite working for me. I am using following:

    var rationale = await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Plugin.Permissions.Abstractions.Permission.Location);
    if (rationale)

    but ShouldShowRequestPermissionRationaleAsync is returning false?

  • SivaShankarArumugamSivaShankarArumugam USMember ✭✭✭

    @JamesMontemagno It is possible to show custom UI for request permission if the permission is not granted.

  • BrianEricksonBrianErickson USMember ✭✭

    The plugin appears to be a little broke when using Windows 10. I am using your sample called PermissionsSample. Specifically asking for the GeoLocation permission.

    UWP:
    If you answer no to the initial permission prompt, the plugin returns 'Granted' from there after. Of course, trying to get the current location fails. Verified using the actual Windows 10 function(GeolocationAccessStatus) that access is denied...

    Clicking on the 'Open Settings' button does nothing.

    Android:
    Works fine.

    IOS:
    Not tested.

    Xaramin Forms is up-to-date., Windows 10 is up-to-date., Visual Studio is up-to-date. I'm running on a Surface Pro. with 8Gig memory.

  • BrianEricksonBrianErickson USMember ✭✭

    Plugin is still broke for UWP (as far as I'm concerned). Just added a few lines of code so I can use with actual Windows API. So, I use the plugin for Android but have uninstalled it for UWP. Everything is now fine.

2»
Sign In or Register to comment.