Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the type of an extra in a bundle held by intent?

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?

like image 702
tyler Avatar asked Aug 23 '11 15:08

tyler


2 Answers

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.

like image 97
Michael Avatar answered Oct 12 '22 23:10

Michael


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 Strings before sending them, and retrieve all of them as Strings :

    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 Objects (see doc):

    Object o = bundle.get(key)
    
like image 22
Shlublu Avatar answered Oct 13 '22 01:10

Shlublu