Android marshmallow request permission?

后端 未结 24 2092
無奈伤痛
無奈伤痛 2020-11-21 06:40

I am currently working on an application that requires several \"dangerous\" permissions. So I tried adding \"ask for permission\" as required in Android Marshmallow(API Lev

24条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 07:08

    It may be a cleaner way. Add all your permissions in an array like

    private static final String[] INITIAL_PERMS={
                android.Manifest.permission.ACCESS_FINE_LOCATION,
                android.Manifest.permission.ACCESS_COARSE_LOCATION
        };
        private static final int INITIAL_REQUEST=1337;
    

    Whatever your permision is create method for each permision

    @RequiresApi(api = Build.VERSION_CODES.M)
    private boolean canAccessFineLocation() {
        return(hasPermission(Manifest.permission.ACCESS_FINE_LOCATION));
    }
    
    @RequiresApi(api = Build.VERSION_CODES.M)
    private boolean canAccessCoarseLocation() {
        return(hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION));
    }
    
    @RequiresApi(api = Build.VERSION_CODES.M)
    private boolean hasPermission(String perm) {
        return(PackageManager.PERMISSION_GRANTED == checkSelfPermission(perm));
    }
    

    Call this method in onCreate

     if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
          if(!canAccessCoarseLocation() || !canAccessFineLocation()){
                requestPermissions(INITIAL_PERMS, INITIAL_REQUEST);
            }
     }
    

    Now override onRequestPermissionsResult

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    
        if(requestCode == INITIAL_REQUEST){
            if (canAccessFineLocation() && canAccessCoarseLocation())  {
                //call your method
            }
            else {
                //show Toast or alert that this permissions is neccessary
            }
        }
    }
    

提交回复
热议问题