Android Marshmallow Location Permission handling

前端 未结 2 835
夕颜
夕颜 2021-01-16 03:05

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

相关标签:
2条回答
  • 2021-01-16 03:39
        if (Build.VERSION.SDK_INT >= 23) {
           if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
        //here req again for Permission
        }
    }
    
    0 讨论(0)
  • 2021-01-16 03:40

    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
               }
            }
    
        }
    
    0 讨论(0)
提交回复
热议问题