Android棉花糖位置权限处理 [英] Android Marshmallow Location Permission handling

查看:90
本文介绍了Android棉花糖位置权限处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Android Marshmallow运行时权限.我要求用户提供位置许可,假设他已允许获取位置并且我已经开始获取位置,但是现在用户已拒绝了应用程序设置的许可.现在应用程序崩溃了.我该如何处理?请帮忙.

I am working on Android Marshmallow runtime permissions. I asked user for location permission, suppose he has allowed to get the location and i have started getting location but now user has denied the permission from settings of application. Now application has crashed. How can i handle it? Please help.

推荐答案

这对我有用!!!在应用程序的您的启动活动中,执行以下操作,

This is worked for me !!! In Your Splash Activity of your application do the following,

注意::如果用户在一段时间后禁用该权限,则这些代码段将不允许进入应用程序而不会崩溃,它会要求一个对话框来允许该所需的权限.

Note: If user disables the permission after some time, these piece of code will not allow to get into the application without any crashes, it asks a dialog to allow that needed permission.

1)为请求代码声明一个int变量,

1) Declare an int variable for request code,

private static final int REQUEST_CODE_PERMISSION = 2;

2)声明一个具有所需权限名称的字符串,

2) Declare a string with the permissions name that you need,

String mPermission = Manifest.permission.ACCESS_FINE_LOCATION,

3)接下来,检查onCreate方法上运行时权限的条件,

3) Next Check the condition for runtime permission on your onCreate method,

 try {
                if (ActivityCompat.checkSelfPermission(this, mPermission)
                        != MockPackageManager.PERMISSION_GRANTED) {

                    ActivityCompat.requestPermissions(this,
                            mPermission, REQUEST_CODE_PERMISSION);

                  // If any permission above not allowed by user, this condition will execute every time, else your else part will work
                } 
            } catch (Exception e) {
                e.printStackTrace();
            }

4)现在声明onRequestPermissionsResult方法以检查请求代码,

4) Now Declare onRequestPermissionsResult method to check the request code,

@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.e("Req Code", "" + requestCode);
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (grantResults.length == 1 &&
                    grantResults[0] == MockPackageManager.PERMISSION_GRANTED ) {

               // Success Stuff here

            }
         else{
               // Failure Stuff
           }
        }

    }

这篇关于Android棉花糖位置权限处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆