在服务中调用 getIntent 方法 [英] Calling getIntent Method in service
问题描述
我必须将参数从 MyActivity.class 传递到 TestService.class.MyActivity 是一个 Activity 类,而 TestService 是我为发送消息而制作的服务.我必须将参数从 Activity 传递给服务,但是当我在服务类中调用 Intent i = getIntent();
时,出现错误 getIntent() 未定义.
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.
那么,如何将参数从我的活动发送到服务?
So, how can I send parameters from my Activity to Service?
推荐答案
像这样开始你的服务;
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");
因此您可以从 onHandleIntent 或 onStartCommand Intent 参数访问您的参数.(取决于您运行的服务类型)例如;
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;
服务
protected void onStartCommand (Intent intent, int flags, int startId) {
data=(String) intent.getExtras().get("data");
}
public int onStartCommand (Intent Intent, int flags, int startId)
IntentService
protected void onHandleIntent(Intent intent) {
data=(String) intent.getExtras().get("data");
}
保护抽象无效 onHandleIntent (Intent意图)
这篇关于在服务中调用 getIntent 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!