c# - Xamarin Android 请求运行时权限不起作用

标签 c# android xamarin xamarin.forms xamarin.android

所以我试图请求用户允许在我尝试创建的应用程序上使用 Location。我已经在 Android Manifest 中包含了权限

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

在我的启动画面所在的 SplashActivity 页面中以及我希望向用户显示我的权限的位置我已将以下代码放入:

namespace Cabiee.Droid
{
[Activity(Theme  = "@style/Theme.Splash",
    MainLauncher = true,
    NoHistory = true,
    Icon = "@drawable/CabieBackground")]
public class SplashActivity : Activity
{

    protected async override void OnCreate(Bundle savedInstanceState)
    {
        await TryToGetPermissions();


        base.OnCreate(savedInstanceState);
        System.Threading.Thread.Sleep(500);
        StartActivity(typeof(Login));

        // Create your application here
    }


    #region RuntimePermissions

    async Task TryToGetPermissions()
    {
        if ((int)Build.VERSION.SdkInt >= 23)
        {
            await GetPermissionsAsync();
            return;
        }


    }
    const int RequestLocationId = 0;

    readonly string[] PermissionsGroupLocation =
        {
                        //TODO add more permissions
                        Manifest.Permission.AccessCoarseLocation,
                        Manifest.Permission.AccessFineLocation,
         };
    async Task GetPermissionsAsync()
    {
        const string permission = Manifest.Permission.AccessFineLocation;

        if (CheckSelfPermission(permission) == (int)Android.Content.PM.Permission.Granted)
        {
            //TODO change the message to show the permissions name
            Toast.MakeText(this, "Special permissions granted", ToastLength.Short).Show();
            return;
        }

        if (ShouldShowRequestPermissionRationale(permission))
        {
            //set alert for executing the task
            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.SetTitle("Permissions Needed");
            alert.SetMessage("The application need special permissions to continue");
            alert.SetPositiveButton("Request Permissions", (senderAlert, args) =>
            {
                RequestPermissions(PermissionsGroupLocation, RequestLocationId);
            });

            alert.SetNegativeButton("Cancel", (senderAlert, args) =>
            {
                Toast.MakeText(this, "Cancelled!", ToastLength.Short).Show();
            });

            Dialog dialog = alert.Create();
            dialog.Show();


            return;
        }

        RequestPermissions(PermissionsGroupLocation, RequestLocationId);

    }
    public override async void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        switch (requestCode)
        {
            case RequestLocationId:
                {
                    if (grantResults[0] == (int)Android.Content.PM.Permission.Granted)
                    {
                        Toast.MakeText(this, "Special permissions granted", ToastLength.Short).Show();

                    }
                    else
                    {
                        //Permission Denied :(
                        Toast.MakeText(this, "Special permissions denied", ToastLength.Short).Show();

                    }
                }
                break;
        }
        //base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    #endregion
}

但是,不会要求用户提供权限。我认为这可能与 await TryToGetPermissions(); 有关。代码开头的行实际上并未调用 TryToGetPermissions,因此它不起作用。

如有任何帮助,我们将不胜感激。

谢谢!

最佳答案

对于完全相同的事情,我有一个可行的解决方案如下:

在您的 OnCreate 方法中检查现有权限:

 if (!(CheckPermissionGranted(Manifest.Permission.AccessCoarseLocation) &&
            CheckPermissionGranted(Manifest.Permission.AccessFineLocation)))
        {
            RequestLocationPermission();
        }
        else
        {
            InitializeLocationManager();
        }
        InitPageWidgets();

其中 Check permission Granted 是这样的方法:

 [Export]
    public bool CheckPermissionGranted(string Permissions)
    {
        // Check if the permission is already available.
        if (ActivityCompat.CheckSelfPermission(this, Permissions) != Permission.Granted)
        {
            return false;
        }
        else
        {
            return true;
        }


    }

请求权限代码如下所示:

  private void RequestLocationPermission()
    {
        if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessFineLocation))
        {
            // Provide an additional rationale to the user if the permission was not granted
            // and the user would benefit from additional context for the use of the permission.
            // For example if the user has previously denied the permission.
            ActivityCompat.RequestPermissions(this, PermissionsLocation, REQUEST_LOCATION);

        }
        else
        {
            // Camera permission has not been granted yet. Request it directly.
            ActivityCompat.RequestPermissions(this, PermissionsLocation, REQUEST_LOCATION);
        }
    }

关于c# - Xamarin Android 请求运行时权限不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55172586/

相关文章:

c# - 如何检查我的列表是否包含具有特定条件的字符串

c# - 使用 IIS .Net ASP.Net 中的 AWS S3 API 时,对象引用未设置为对象的实例

Android ObjectBox.getAll() 返回 null,即使 objectBox.count 为 5

android - Theme.Dialog 创建的屏幕太小

iOS 分享扩展如何支持 *.wav 文件

c# - 删除 EnumDropDownListFor 框顶部的空白/空条目

C# 使用隐式 ssl 发送电子邮件

android - Xamarin Studio 中未呈现自定义可绘制对象

c# - Xamarin.Forms.Xaml.XamlParseException : MarkupExtension not found for trans:Translate using a PCL in Release Mode

c# - 使用 csvHelper 动态创建列