Read and Write permission for storage and gallery usage for marshmallow

tiger picture tiger · Mar 8, 2016 · Viewed 39.1k times · Source

I am developing an android app in which it is required to provide permission for Read and write external storage. My requirement is to select a picture from gallery and use it in my app. Everything is working fine except Marshmallow devices. I want to provide permission for Marshmallow. Can anyone help me with this?

Answer

Khan picture Khan · Mar 8, 2016

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