为什么ActivityCompat.requestPermissions()只接受0-255之间的整数请求码?
Why does ActivityCompat.requestPermissions() only accept an integer request code between 0-255?
最近更新了一个app,targetSdkVersion为23,实现了各种权限请求。我最初尝试使用 ActivityCompat.requestPermissions() 导致从 FragmentActivity 的内部抛出 IllegalArgumentException:
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
但是,如果请求代码在 0-255 之间,则一切正常,权限请求按预期工作。
int REQUEST_CODE_B = 101;
ActivityCompat.requestPermissions(new String[ {Manifest.permission.WRITE_CONTACTS}, REQUEST_CODE_B); // works correctly
那么问题来了,有什么理由像这样限制API中整数的可能取值呢?可以使用字节来提供相同的信息,但是(显然)已经有意识地决定使用整数来代替。这仅仅是允许未来可扩展性的情况吗?
在似乎抛出此异常的地方引用 the source code to 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
.
最近更新了一个app,targetSdkVersion为23,实现了各种权限请求。我最初尝试使用 ActivityCompat.requestPermissions() 导致从 FragmentActivity 的内部抛出 IllegalArgumentException:
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
但是,如果请求代码在 0-255 之间,则一切正常,权限请求按预期工作。
int REQUEST_CODE_B = 101;
ActivityCompat.requestPermissions(new String[ {Manifest.permission.WRITE_CONTACTS}, REQUEST_CODE_B); // works correctly
那么问题来了,有什么理由像这样限制API中整数的可能取值呢?可以使用字节来提供相同的信息,但是(显然)已经有意识地决定使用整数来代替。这仅仅是允许未来可扩展性的情况吗?
在似乎抛出此异常的地方引用 the source code to 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
.