Read and Write permission for storage and gallery usage for marshmallow

For writing a file in storage, First,need to add write permission in manifest.xml,

Then, In Android 6, it contains a permission system for certain tasks. Each application can request the required permission on runtime. So let’s open Activity class add below code for requesting runtime permission.

check your application has a runtime write permission using,

override fun onRequestPermissionsResult(requestCode: Int,
    permissions: Array<out String>,
    grantResults: IntArray) {

    when(requestCode)  {

        100 -> {
            if (grantResults.size > 0 && permissions[0] == Manifest.permission.WRITE_EXTERNAL_STORAGE) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                
                }
            }

        }
    }

}

Read through Runtime permissions - Android M and its reference project.

Permissions flow has changed requiring the permissions to be asked at runtime, preferably, as and when required. With the same.. permissions have also been categorised into Normal and Dangerous which will also lead to permission groups.


It can be achieved something as following...

public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback{

  private static final int REQUEST_WRITE_PERMISSION = 786;

  @Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == REQUEST_WRITE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {            
        openFilePicker();
    }
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    requestPermission();
  }

  private void requestPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
    } else {
        openFilePicker();
    }
  }
}