我最近更新了一个应用程序,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 中限制整数的可能值?可以使用字节来提供相同的信息,但是(显然)已经有意识地决定使用整数来代替。这仅仅是允许 future 可扩展性的情况吗?
最佳答案
引用 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
中是这样。
关于java - 为什么 ActivityCompat.requestPermissions() 只接受 0-255 之间的整数请求码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34663973/