[英]Send data from Activity to Service
如何将数据从当前Activity
发送到在特定时间运行的后台Service
类? 我试图设置为Intent.putExtras()
但是在Service
类中却没有
调用Service
Activity
类中的代码。
Intent mServiceIntent = new Intent(this, SchedulerEventService.class);
mServiceIntent.putExtra("test", "Daily");
startService(mServiceIntent);
Service
类中的代码。 我试图放入onBind()
和onStartCommand()
。 这些方法都不能打印该值。
@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;
}
您的代码应为onStartCommand
。 如果你从来没有调用bindService
您的活动onBind
不会被调用,并使用getStringExtra()
代替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
}
如果要传递可以放入Intent中的原始数据类型,建议使用IntentService。 要启动IntentService,请输入您的活动:
startService(new Intent(this, YourService.class).putExtra("test", "Hello work");
然后创建一个扩展IntentService类的服务类:
public class YourService extends IntentService {
String stringPassedToThisService;
public YourService() {
super("Test the service");
}
@Override
protected void onHandleIntent(Intent intent) {
stringPassedToThisService = intent.getStringExtra("test");
if (stringPassedToThisService != null) {
Log.d("String passed from activity", stringPassedToThisService);
// DO SOMETHING WITH THE STRING PASSED
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.