Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ActivityCompat.requestPermissions() only accept an integer request code between 0-255?

I recently updated an app to a targetSdkVersion of 23, and implemented a request for various permissions. My initial attempt using ActivityCompat.requestPermissions() caused an IllegalArgumentException to be thrown from the internals of FragmentActivity:

int REQUEST_CODE_A = 9001;
ActivityCompat.requestPermissions(new String[ {Manifest.permission.WRITE_CONTACTS}, REQUEST_CODE_A); // crashes

java.lang.IllegalArgumentException: Can only use lower 8 bits for requestCode

However, if the request code is between 0-255, everything is fine and the permission request works as expected.

int REQUEST_CODE_B = 101;
ActivityCompat.requestPermissions(new String[ {Manifest.permission.WRITE_CONTACTS}, REQUEST_CODE_B); // works correctly

So the question is, what reasons are there for restricting the possible values of an integer in an API like this? The same information could be supplied using a byte, but a conscious decision has (apparently) been made to use an integer instead. Is this simply a case of allowing future extensibility?

like image 485
fractalwrench Avatar asked Sep 02 '26 20:09

fractalwrench


1 Answers

Quoting the source code to FragmentActivity where this exception appears to be thrown:

    // We use 8 bits of the request code to encode the fragment id when
    // requesting permissions from a fragment. Hence, requestPermissions()
    // should validate the code against that but we cannot override it as
    // we can not then call super and also the ActivityCompat would call
    // back to this override. To handle this we use dependency inversion
    // where we are the validator of request codes when requesting
    // permissions in ActivityCompat.

startActivityForResult() has a 16-bit limit on the request code, at least in FragmentActivity.

like image 93
CommonsWare Avatar answered Sep 05 '26 09:09

CommonsWare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!