在服务调用getIntent方法 [英] Calling getIntent Method in service

查看:143
本文介绍了在服务调用getIntent方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不得不从MyActivity.class到TestService.class传递参数。 MyActivity是活动类和测试服务是我已经发送消息的服务。我必须从活动类参数传递给服务类。但是当我打电话意图I = getIntent(); 在服务类中,我得到一个错误的 getIntent()是未定义。请给我建议,我怎么可以把参数从我的活动类的服务还是有使用getIntent()任何替代方法。在此先感谢

I have to pass parameter from MyActivity.class to TestService.class. MyActivity is a Activity class and Test Service is a Service that i have made for sending messages. I have to pass parameter from Activity Class to the Service class. but when i call Intent i = getIntent(); in service class, I am getting an error getIntent() is undefined. Please give me suggestion how can i take parameter from my activity class in service or is there any alternate method to use getIntent(). Thanks in Advance

推荐答案

启动您的服务是这样;

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"); 

所以,你可以从任一onHandleIntent或onStartCommand意图参数访问参数。 (具体取决于您正在运行的服务的类型)在实施例;

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"); 
}

<一个href="http://developer.android.com/reference/android/app/Service.html#onStartCommand%28android.content.Intent,%20int,%20int%29">public INT onStartCommand(意向意图,INT标志,INT startId)

IntentService

protected void onHandleIntent(Intent intent) {
    data=(String) intent.getExtras().get("data"); 
}

<一个href="http://developer.android.com/reference/android/app/IntentService.html#onHandleIntent%28android.content.Intent%29">protected抽象无效onHandleIntent(意向意图)

这篇关于在服务调用getIntent方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆