使用 Intent 将数据从 Activity 传递到 Service [英] Pass data from Activity to Service using an Intent
问题描述
如何获取从调用 Activity
传递过来的 Android Service
中的数据?
How do I get data within an Android Service
that was passed from an invoking Activity
?
推荐答案
First Context(可以是 Activity/Service 等)
对于服务,你需要覆盖 onStartCommand 那里你可以直接访问intent
:
For Service, you need to override onStartCommand there you have direct access to intent
:
Override
public int onStartCommand(Intent intent, int flags, int startId) {
您有几个选择:
1) 使用 Bundlehttp://developer.android.com/reference/android/content/Intent.html" rel="noreferrer">意图:
1) Use the Bundle from the Intent:
Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);
2) 创建一个新的 Bundle
2) Create a new Bundle
Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.extras.putString(key, value);
mIntent.putExtras(mBundle);
3) 使用 putExtra() Intent 的快捷方法
3) Use the putExtra() shortcut method of the Intent
Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);
新上下文(可以是活动/服务等)
Intent myIntent = getIntent(); // this getter is just for example purpose, can differ
if (myIntent !=null && myIntent.getExtras()!=null)
String value = myIntent.getExtras().getString(key);
}
注意: 捆绑包具有适用于所有原始类型、Parcelable 和 Serializable 的get"和put"方法.我只是出于演示目的使用字符串.
NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.
这篇关于使用 Intent 将数据从 Activity 传递到 Service的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!