How to determine the type of extra in the package contained in the intent?

I am trying to pass arbitrary data to BroadcastReceiver through its Intent .

So I can 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 it to BroadcastReceiver

I want to iterate through Intent.getExtras() with something like keySet() , but I would also like to be able to get the key value without having to hard call the methods like .getStringExtra() or .getBooleanExtra() .

How does a person do this?

+8
android android-intent broadcastreceiver
source share
2 answers

You can use the following code to get an object of any time from Intent :

 Bundle bundle = intent.getExtras(); Object value = bundle.get("key"); 

You can then determine the actual type of value using the Object methods.

+15
source share

You can view thye keys without knowing the type of values ​​using keySet() . It returns you a String set into which you can iterate (see doc ).

But for values, as a rule, you should use a typed method ( getStringExtra() , getBooleanExtra() , etc.): this is due to the fact that Java itself is typing.

If you want to send arbitrary types of data to BroadcastReceiver , you must either:

  • convert all your additions to String before sending them and extract all of them as String :

     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() Bundle method, which returns an Object (see doc ):

     Object o = bundle.get(key) 
+4
source share

All Articles