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.
The easiest way to do this would be to pass the session id to the signout activity in the Intent you're using to start the activity: Intent intent = new Intent(getBaseContext(), SignoutActivity. class); intent. putExtra("EXTRA_SESSION_ID", sessionId); startActivity(intent);
You can add extra data with various putExtra() methods, each accepting two parameters: the key name and the value. You can also create a Bundle object with all the extra data, then insert the Bundle in the Intent with putExtras() .
There are two intents available in android as Implicit Intents and Explicit Intents.
Retrieving data from intent Once you start the activity, You'll be able to get the data attached in the next activity [or services, BoradCast receivers.. etc] being started. to retrieve the data, we use the method getExtra() on the NextActivity from the intent.
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)
You can do the following to add information into the intent bundle:
Intent i = new Intent(MessageService.this, ViewMessageActivity.class); i.putExtra("message", "value"); startActivity(i);
Then in the activity you can retrieve like this:
Bundle extras = getIntent().getExtras(); String message = extras.getString("message");
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