android studio ask write permission kotlin code example

Example: runtime permission android

if(checkPermission()){
 // do operation
}
else{
  // request Permission in Activity
   requestPermissions(getApplicationContext(),
   new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE},200);
  // request Permission in Fragmemt
   requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE}, 200);
}
private boolean checkPermission() {
     int writePerm =   ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
     int readPerm = ContextCompat.checkSelfPermission(context,Manifest.permission.READ_EXTERNAL_STORAGE);
     return writePerm== PackageManager.PERMISSION_GRANTED && readPerm==PackageManager.PERMISSION_GRANTED;
    }
    
   @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==Constants.PERMISSION_REQUEST_CODE){
            if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED
            && grantResults[1]==PackageManager.PERMISSION_GRANTED){
               // do Operation
            }
            else{
                Toast.makeText(context,"Permission Denied",Toast.LENGTH_SHORT).show();
            }
        }
    }