我最近将应用程序更新为23的targetSdkVersion,并实现了对各种权限的请求.我最初尝试使用ActivityCompat.requestPermissions()导致从FragmentActivity的内部抛出IllegalArgumentException:
int REQUEST_CODE_A = 9001; ActivityCompat.requestPermissions(new String[ {Manifest.permission.WRITE_CONTACTS}, REQUEST_CODE_A); // crashes
java.lang.IllegalArgumentException:对于requestCode只能使用低8位
但是,如果请求代码在0到255之间,则一切正常,并且权限请求按预期工作.
int REQUEST_CODE_B = 101; ActivityCompat.requestPermissions(new String[ {Manifest.permission.WRITE_CONTACTS}, REQUEST_CODE_B); // works correctly
所以问题是,在这样的API中限制整数的可能值的原因是什么?可以使用一个字节提供相同的信息,但是(显然)有意识地决定使用整数.这只是一个允许未来可扩展性的案例吗?
将源代码FragmentActivity
引用到抛出此异常的位置:
// 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()
对请求代码有16位限制,至少在FragmentActivity
.