问题
I am writing an application where Activity A launches Activity B using
startActivityForResult(intent, -101);
but when called, it responded back with following error log:
E/AndroidRuntime( 1708): java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode
E/AndroidRuntime( 1708): at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:837)
Probably it could be -101 but I am not sure. Does any one have any idea on this?
回答1:
You need to pass a positive number to startActivityForResult.
回答2:
You get this exception only in android.support.v4.app.FragmentActivity and not when you use android.app.Activity.
startActivityForResult() in FragmentActivity requires the requestCode to be of 16 bits, meaning the range is from 0 to 65535.
Also, validateRequestPermissionsRequestCode in FragmentActivity requires requestCode to be of 16 bits, meaning the range is from 0 to 65535.
For more info(if you want to see the source code) : https://stackoverflow.com/a/33331459/4747587
回答3:
It is also good to mention that this may happen if you use a number greater than 2^16 / 2 (which is 32768), so there's basically 2^15 options to not to screw this up.
Explanation: 16 bits can represent one of 65536 numbers, however, half of them are negative.
回答4:
You can only use lower 16 bits for requestCode means -- in binary terms -- you can use
0000000000000000 (16 bits) to 1111111111111111 (16 bits).
In decimal ("number") terms, this allows for 2^16 = 65536 combinations. Therefore, you can only use the numbers 0 all the way through 65535.
You also cannot use negative numbers.
回答5:
The right answer is that you should use a 16 bits number for this purpose.
The most safe solution for that is to always set your request code as short. If programmer attempts to write number more than 16 bits then the IDE won't let you to proceed because there will be an error.
来源:https://stackoverflow.com/questions/25529865/java-lang-illegalargumentexception-can-only-use-lower-16-bits-for-requestcode