首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Xamarin Android请求运行时权限不起作用

Xamarin Android请求运行时权限不起作用
EN

Stack Overflow用户
提问于 2019-03-14 21:53:06
回答 2查看 9.7K关注 0票数 4

因此,我试图请求用户允许我在我试图创建的应用程序上使用位置。我已经在Android中包含了许可

代码语言:javascript
运行
复制
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

在我的SplashActivity页面中,Splash屏幕所在,以及我希望用户看到我的权限的地方,我已经将以下代码放入其中:

代码语言:javascript
运行
复制
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
}

然而,用户并没有被要求做这些事。我认为这可能与等待TryToGetPermissions();代码开始时的行有关,代码实际上并没有调用TryToGetPermissions,因此它无法工作。

任何帮助都将不胜感激。

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-03-15 05:58:48

对于同样的事情,我有一个工作解决方案,如下所示:

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

代码语言:javascript
运行
复制
 if (!(CheckPermissionGranted(Manifest.Permission.AccessCoarseLocation) &&
            CheckPermissionGranted(Manifest.Permission.AccessFineLocation)))
        {
            RequestLocationPermission();
        }
        else
        {
            InitializeLocationManager();
        }
        InitPageWidgets();

授予检查权限的方法如下所示:

代码语言:javascript
运行
复制
 [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;
        }


    }

请求权限代码如下所示:

代码语言:javascript
运行
复制
  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);
        }
    }
票数 2
EN

Stack Overflow用户

发布于 2019-03-15 04:06:51

如果您不需要异步/等待,下面是我在我的应用程序中所做的,我需要相机权限。它对我的需求非常有用,也许它也能满足你的需求。

您的实现将更加简单,因为您不需要在OnRequestPermissionsResult()中迭代多个结果。我不得不这样做,因为我的应用程序需要保存图片,因此需要相机和WriteExternalStorage权限才能加载相机接口/活动。

代码语言:javascript
运行
复制
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true, ScreenOrientation = ScreenOrientation.Landscape)]
public class MainLoaderActivity : AppCompatActivity {

    private const string LOG_TAG = "CAMERA2_LOG";        
    private const int PERMISSION_REQUEST_CODE_CAMERA_USAGE = 4500;  // Arbitrary number to identify our permissions required for camera app usage
    private Button btnLoadCameraActivity;

    protected override void OnCreate(Bundle savedInstanceState) {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.main_loader);
        btnLoadCameraActivity = FindViewById<Button>(Resource.Id.btnLoadCameraActivity);
        btnLoadCameraActivity.Click += btnLoadCameraActivity_Click;
    }

    private void btnLoadCameraActivity_Click(object sender, EventArgs e) {
        // Using the camera on Android 6.0 and later requires a run-time permissions granting by the user.
        // So, check to see if user manually enabled in Settings, or previously was prompted in this app and was granted access.  If not, we'll prompt them...

        if (CheckSelfPermission(Android.Manifest.Permission.Camera) == Permission.Granted && 
            CheckSelfPermission(Android.Manifest.Permission.WriteExternalStorage) == Permission.Granted) {
            // We have both permissions necessary to run the Camera interface...
            StartActivity(typeof(CameraActivity));
            return;
        }

        // If we get here, at least one of the required permissions hasn't been approved, so find out which one and request accordingly...
        var listPermissions = new System.Collections.Generic.List<string>();

        // Build array of permissions needed for Camera usage
        if (CheckSelfPermission(Android.Manifest.Permission.Camera) != Permission.Granted) {
            Log.Warn(LOG_TAG, "CheckSelfPermission(Camera) not yet granted - will prompt user for permission");
            listPermissions.Add(Android.Manifest.Permission.Camera);
        }
        if (CheckSelfPermission(Android.Manifest.Permission.WriteExternalStorage) != Permission.Granted) {
            Log.Warn(LOG_TAG, "CheckSelfPermission(WriteExternalStorage) not yet granted - will prompt user for permission");
            listPermissions.Add(Android.Manifest.Permission.WriteExternalStorage);
        }

        // Make the request with the permissions needed...and then check OnRequestPermissionsResult() for the results
        RequestPermissions(listPermissions.ToArray(), PERMISSION_REQUEST_CODE_CAMERA_USAGE);
    }

    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults) {
        Log.Info(LOG_TAG, $"OnRequestPermissionsResult(requestCode={requestCode} - Permissions Count={permissions.Length} - GrantResults Count={grantResults.Length})");
        switch (requestCode) {
            // To use the camera, the user must grant privs to the Camera as well as writing to external storage, so this case checks both
            case PERMISSION_REQUEST_CODE_CAMERA_USAGE: {                    
                for (var i = 0; i < permissions.Length; i++) {
                    Log.Info(LOG_TAG, $"Checking permission for {permissions[i]}...");
                    if (grantResults[i] != Permission.Granted) {
                        Log.Info(LOG_TAG, $"Permission Denied for {permissions[i]}!");
                        Toast.MakeText(this, "You must approve all permissions prompted to use the camera.", ToastLength.Long).Show();
                        return;
                    }
                    Log.Info(LOG_TAG, $"Permission Granted for {permissions[i]}.");
                }
                // If we get here then all the permissions we requested were approved and we can now load the Camera interface
                StartActivity(typeof(CameraActivity));
                break;
            }
        }
    }

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55172586

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档