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

  • ShubhuuuShubhuuu 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

  • ShubhuuuShubhuuu 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)
        {
        }
    }
    

    }

  • ShubhuuuShubhuuu 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.

2»
Sign In or Register to comment.