将数据从服务传递到另一个服务

时间:2010-11-23 10:08:23

标签: android service android-intent

我有两项服务: 数据提供者和接收者。

我尝试这样做:

PROVIDER:

Intent i1 = new Intent(feasibilityEngine.this, SOSFeeder.class);
i1.putExtra(SENSOR_STRING, "f[i]");
startService(i1);

RECEIVER

Intent intent = getIntent();
Bundle b = new Bundle();
int i = b.getInt(SENSRO_STRING);

但我无法使用getIntent()。

有人可以帮帮我吗? TNKS

2 个答案:

答案 0 :(得分:0)

您可以将SENSRO_STRING的值检索为:

Bundle b = getIntent().getExtras();
int i = b.getInt(SENSRO_STRING);

如果您在BroadcastReceiver中,例如在覆盖的onReceived方法中,您可以调用:

@Override
public void onReceive(Context context, Intent intent)
{
     Bundle b = intent.getExtras();
     int i = b.getInt(SENSRO_STRING);

答案 1 :(得分:0)

无需调用getInent(),您的意图将被传递给onStartCommand()中的接收器服务,该服务将是您从startService()调用的入口点。

here 修改的示例代码。

接收服务:

// This is the old onStart method that will be called on the pre-2.0
// platform.  On 2.0 or later we override onStartCommand() so this
// method will not be called.
@Override
public void onStart(Intent intent, int startId) {
    handleCommand(intent);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handleCommand(intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}

private void handleCommand(Intent intent) {
    // should this be getStringExtra instead?
    int i = intent.getIntExtra(SENSRO_STRING, -1);
}