开发者

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 thr开发者_StackOverflow中文版ough 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 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)
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜