Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I might have misunderstood how intents are supposed to be used, so I might be asking the wrong thing here. If that's the case, please help me get on the right track with this anyway...

I've just started working on an android app that will poll my server for messages every so often, and when a new message is available, I want to show it to the user. I'm trying to implement this by having a Service that polls the server, and when a new message is received the service should give the message to an Activity that shows it.

To facilitate this communication, I'm trying to create an Intent with ACTION_VIEW, but I can't figure out how to give the message to the activity. Is there no way to pass a string or a regular Java object via the intent?

For what it's worth, this is what I'd like to do:

getApplication().startActivity(new Intent(MessageService.this, ViewMessageActivity.class, message));

but of course, that doesn't even compile.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
475 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use the Intent bundle to add extra information, like so:

Intent i = new Intent(MessageService.this, ViewMessageActivity.class);
i.putExtra("name", "value");

And on the receiving side:

String extra = i.getStringExtra("name");

Or, to get all the extras as a bundle, independently of the type:

Bundle b = i.getExtras();

There are various signatures for the putExtra() method and various methods to get the data depending on its type. You can see more here: Intent, putExtra.

EDIT: To pass on an object it must implement Parcelable or Serializable, so you can use one of the following signatures:

putExtra(String name, Serializable value)

putExtra(String name, Parcelable value)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...