如何创建一个Android意图承载的数据? [英] How do I create an android Intent that carries data?
问题描述
我可能误会了怎么意图都被认为是使用,所以我可能会在这里问错了东西。如果是这样的话,请帮我在正确的轨道与此反正...
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...
我刚刚开始工作在Android应用程序,将轮询我的服务器消息每隔一段时间,当一个新的消息是可用的,我想把它显示给用户。我试图通过具有服务来实现这个
是轮询服务器,并在接收到新信息的服务应该给消息发送给活动
显示它。
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.
要促进这种沟通,我试图创建一个意图
与 ACTION_VIEW
,但我不能弄清楚如何给邮件活动。请问有没有办法通过一个字符串或通过一个意图常规的Java对象?
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.
推荐答案
使用的意图包中添加额外的信息,像这样:
Use the Intent bundle to add extra information, like so:
Intent i = new Intent(MessageService.this, ViewMessageActivity.class);
i.putExtra("name", "value");
和接收端:
String extra = i.getStringExtra("name");
或者,让所有的演员独立的类型为一扎,:
Or, to get all the extras as a bundle, independently of the type:
Bundle b = i.getExtras();
有各种签名的 putExtra()
方法和各种方法来获取数据,根据其类型。你可以在这里看到更多:意图,<一个href="http://developer.android.com/reference/android/content/Intent.html#putExtra%28java.lang.String,%20double%5B%5D%29">putExtra.
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.
编辑::要传递的对象必须实现 Parcelable上或序列化,这样你就可以使用下面的签名之一:
To pass on an object it must implement Parcelable or Serializable, so you can use one of the following signatures:
<一个href="http://developer.android.com/reference/android/content/Intent.html#putExtra%28java.lang.String,%20java.io.Serializable%29">putExtra(String名称,序列化值)
<一个href="http://developer.android.com/reference/android/content/Intent.html#putExtra%28java.lang.String,%20android.os.Parcelable%29">putExtra(String名,Parcelable值)
这篇关于如何创建一个Android意图承载的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!