Android Marshmallow Location Permission handling

旧街凉风 提交于 2019-12-01 12:05:50

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) Declare an int variable for request code,

private static final int REQUEST_CODE_PERMISSION = 2;

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

String mPermission = Manifest.permission.ACCESS_FINE_LOCATION,

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) 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
           }
        }

    }
    if (Build.VERSION.SDK_INT >= 23) {
       if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
    //here req again for Permission
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!