I was planning to use generated resource IDs for all my startActivityForResult()
codes, so that I can use onActivityResult()
in base classes and not have to worry if the derived class used the same code.
Unfortunately it seems that the codes are restricted to 16 bits, and resource IDs are 32 bits. Is there a way to generate unique 16 bit IDs instead?
Actually there is. Moreover you can use standard id as Android resource. Simply just mask your id with 0x0000FFFF
and use it wherever you want as ID for startActivityForResult()
or requestPermissions()
, you may use this simple utility:
public static int normalizeId(int id){
return id & 0x0000FFFF;
}
Why?
Firstly, Lets point to the reason behind that limitation to 16 bit vlaue. It's Fragment/Activity. OS enforces developers to use 16 bit while ID is 32 bit(as integer number) because system always masks id with 0xffff
then shifts it with 16 (<<16) when call comes from Fragment. so it's a unique id marked as fragment target Id.On the other side, the id sent via activity stays as it's, so its activity target Id. Then when results come out, OS knows where to send whether to Fragment or Activity. Lets say we have this id Id=0x0001
Id in startActivityForResult()
in Activity becomes(no-change):
Id=0x0001
Id in startActivityForResult()
in Fragment becomes:
Id=0xFFFF0001
Now how comes we can just ignore the first 16 bit ? lets take a look on anatomy of id of any resource in Android. it composes of three parts as HEX value construction:
PPTTVVVV
PP: represents package id. There are two of them:
- 0x01 (system package ID)
- 0x7f (app package ID)
TT: represents type Id. i.e.:
- 0x0b : array
- 0x01 : attr
- 0x0c : dimen
- 0x10 : color
- 0x0e : bool
- 0x02 : drawable
- .. etc
VVVV: represents real unique identification of specific type of resource under specific package id.
As you can see now that ignoring first 16bit which represents PPTT
will not have impact on your app or leading to conflict with ids. So safely use only VVVV
part which is 16 bit value in startActivityForResult()
or requestPermissions()
I hope that may help you,'.