从活动的数据发送到服务 [英] Send data from Activity to Service
问题描述
如何从当前的活动
将数据发送到一个背景,是在一定的时间运行服务
类?我试图设置为 Intent.putExtras()
,但我没有得到它在<code>服务类
code在活动
类,它调用服务
。
意图mServiceIntent =新意图(这一点,SchedulerEventService.class);
mServiceIntent.putExtra(测试,人民日报);
startService(mServiceIntent);
code在服务
类。我TREID摆在 onBind()
和 onStartCommand()
。这些方法没有打印的价值。
@覆盖
公众的IBinder onBind(意向意图){
//Toast.makeText(this,服务启动,Toast.LENGTH_SHORT).show(); //字符串数据= intent.getDataString(); Toast.makeText(这一点,启动..,Toast.LENGTH_SHORT).show(); Log.d(APP_TAG,intent.getExtras()的getString(测试));
返回null;
}
您code应该onStartCommand。如果你从来没有叫你的活动onBind不会被调用bindService,并使用getStringExtra()而不是getExtras()
@覆盖
公众诠释onStartCommand(意向意图,诠释旗帜,INT startId)
{
Toast.makeText(这一点,启动..,Toast.LENGTH_SHORT).show();
Log.d(APP_TAG,intent.getStringExtra(测试));
返回START_STICKY; //或任何你的旗帜
}
How can I send data from the current Activity
to a background Service
class which is running at certain time? I tried to set into Intent.putExtras()
but I am not getting it in Service
class
Code in Activity
class which calls the Service
.
Intent mServiceIntent = new Intent(this, SchedulerEventService.class);
mServiceIntent.putExtra("test", "Daily");
startService(mServiceIntent);
Code in Service
class. I treid to put in onBind()
and onStartCommand()
. None of these methods prints the value.
@Override
public IBinder onBind(Intent intent) {
//Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
//String data = intent.getDataString();
Toast.makeText(this, "Starting..", Toast.LENGTH_SHORT).show();
Log.d(APP_TAG,intent.getExtras().getString("test"));
return null;
}
Your code should be onStartCommand. If you never call bindService on your activity onBind will not be called, and use getStringExtra() instead of getExtras()
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Toast.makeText(this, "Starting..", Toast.LENGTH_SHORT).show();
Log.d(APP_TAG,intent.getStringExtra("test"));
return START_STICKY; // or whatever your flag
}
这篇关于从活动的数据发送到服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!