Android 在服务中调用 getIntent 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11949248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling getIntent Method in service
提问by CodingDecoding
I have to pass parameter from MyActivity.class to TestService.class. MyActivity is a Activity class and TestService is a Service that I have made for sending messages. I have to pass parameter from Activity to the Service, but when I call Intent i = getIntent();in service class, I am getting an error getIntent() is undefined.
我必须将参数从 MyActivity.class 传递到 TestService.class。MyActivity 是一个 Activity 类,而 TestService 是我为发送消息而制作的服务。我必须将参数从 Activity 传递给服务,但是当我Intent i = getIntent();在服务类中调用时,出现错误getIntent() is undefined。
So, how can I send parameters from my Activity to Service?
那么,如何将参数从我的活动发送到服务?
回答by Lunar
Start your service like this;
像这样启动你的服务;
Intent ir=new Intent(this, Service.class);
ir.putExtra("data", data);
this.startService(ir);
You attach your data as an intent extra.
你附加你的数据作为一个额外的意图。
Then to retrieve the data from the service;
然后从服务中检索数据;
data=(String) intent.getExtras().get("data");
So you can access your parameter from either the onHandleIntent or onStartCommand Intent parameter. (depending on which type of service you are running) For Example;
因此,您可以从 onHandleIntent 或 onStartCommand Intent 参数访问您的参数。(取决于您正在运行的服务类型)例如;
Service
服务
protected void onStartCommand (Intent intent, int flags, int startId) {
data=(String) intent.getExtras().get("data");
}
public int onStartCommand (Intent intent, int flags, int startId)
public int onStartCommand(意图意图,int标志,int startId)
IntentService
意图服务
protected void onHandleIntent(Intent intent) {
data=(String) intent.getExtras().get("data");
}
回答by Atul Bhardwaj
When you start Service with intent(having Data) then that intent is received in methodonStart(Intent intent, int startId)or
当您使用意图(具有数据)启动服务时,该意图将在方法onStart(Intent intent, int startId)或
onStartCommand (Intent intent, int flags, int startId)
{
this **intent** is your intent with data
}
of your Service.So receive your data from this method having intent as parameter
您的 Service.So 从此方法接收您的数据,并将意图作为参数

