如何将数据从当前 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
。如果您从不在您的 Activity 上调用 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
}
关于android - 将数据从 Activity 发送到 Service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15234181/