I am trying to pass arbitrary data to a BroadcastReceiver
through its Intent
.
So I might do something like the following
intent.putExtra("Some boolean", false);
intent.putExtra("Some char", 'a');
intent.putExtra("Some String", "But don't know what it will be");
intent.putExtra("Some long", 15134234124125);
And then pass this to the BroadcastReceiver
I want to iterate through Intent.getExtras()
with something like keySet()
, but I would also like to be able to get the value of the key without having to hard-code calls to methods like .getStringExtra()
, or .getBooleanExtra()
.
How does a person do this?
You can use the following code to get an object of any time from the Intent
:
Bundle bundle = intent.getExtras();
Object value = bundle.get("key");
Then you can determine value
's real type using Object
's methods.
You can browse thye keys without knowing the type of the values using keySet()
. It returns you a set of String
that you can iterate on (see doc).
But for the values, it is normal that you have to use a typed method (getStringExtra()
, getBooleanExtra()
, etc): this is caused by the fact Java itself is typed.
If you would like to send data of arbitrary types to your BroadcastReceiver
, you should either:
convert all your extras to String
s before sending them, and retrieve all of them as String
s :
intent.putExtra("Some boolean", "false");
intent.putExtra("Some char", "a");
intent.putExtra("Some String", "But don't know what it will be");
intent.putExtra("Some long", "15134234124125");
or use the get()
method of the Bundle
that returns Object
s (see doc):
Object o = bundle.get(key)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With