背景位置在 android 11 中不起作用

Background Location does not work in android 11

我有一个用 Xamarin 编写的移动应用程序,请求许可的 class 看起来像这样

 public class AppPermissionsManager
    {
        private readonly string[] _permissions =
        {
            Manifest.Permission.AccessCoarseLocation,
            Manifest.Permission.AccessFineLocation,
            Manifest.Permission.AccessLocationExtraCommands,
            Manifest.Permission.AccessNetworkState,
            Manifest.Permission.AccessWifiState,
            Manifest.Permission.Camera,
            Manifest.Permission.Internet,
            Manifest.Permission.ReadPhoneState,
            Manifest.Permission.ReadExternalStorage,
            Manifest.Permission.WriteExternalStorage
        };

        private readonly string[] _androidQPermissions =
        {
            Manifest.Permission.AccessCoarseLocation,
            Manifest.Permission.AccessFineLocation,
            Manifest.Permission.AccessLocationExtraCommands,
            Manifest.Permission.AccessNetworkState,
            Manifest.Permission.AccessWifiState,
            Manifest.Permission.Camera,
            Manifest.Permission.Internet,
            Manifest.Permission.ReadPhoneState,
            Manifest.Permission.ReadExternalStorage,
            Manifest.Permission.WriteExternalStorage,
            Manifest.Permission.AccessBackgroundLocation
        };

        public static int RequestLocationId = 0;

        public bool CheckPermissions()
        {
            string[] permissions = GetPermissions();

            foreach (var permission in permissions)
            {
                if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, permission) != (int)Permission.Granted)
                {
                    return false;
                }
            }

            return true;
        }

        private string[] GetPermissions()
        {
            return Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Q ? _androidQPermissions : _permissions;
        }

        public void RequestPermissions()
        {
            try
            {
                var permissions = GetPermissions();

                Activity activity = CrossCurrentActivity.Current.Activity;
                ActivityCompat.RequestPermissions(activity, permissions, RequestLocationId);
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, nameof(AppPermissionsManager), MethodBase.GetCurrentMethod().Name);
            }
        }
    }

我的问题是 AccessBackgroundLocation 在 Android11 上不起作用(当用户打开应用程序时,会出现一个空白页面,并且不会记录任何错误)。如果我删除 AccessBackgroundLocation,应用程序可以正常工作(后台定位功能除外)

Background Location Restrictions Android 11+ API 30+

为了访问后台位置,用户必须从“设置”页面启用权限。

编辑

在评论中@lee-m 的帮助下,您问题的答案是在 Android 11+ 中,当您同时请求前景和背景位置时,android 将忽略此请求,并且不会授予任何一个权限。

首先您需要前台位置访问权限,然后是后台。如果您确实需要后台位置,则需要提示您的用户在应用程序的“设置”页面中始终启用“允许”。