aim aim - 5 months ago 23
Android Question

IntentService and Binding Pattern

I have IntentService that should use reference from another service via binding:

public class BaseIntentService extends IntentService implements ServiceConnection {

protected NetworkApi network;

public BaseIntentService() {
super("BaseIntentService");
}

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
network = ((NetworkApiBinder) service).getApi();
// never be invoked
}

@Override
public void onServiceDisconnected(ComponentName name) {
}

@Override
public void onCreate() {
super.onCreate();
bindService(new Intent(this, NetworkApi.impl), this, BIND_AUTO_CREATE);
}

@Override
public void onDestroy() {
super.onDestroy();
unbindService(this);
}

@Override
protected void onHandleIntent(Intent intent) {
// network always null!!!
}
}


But when I'm using binding like this onServiceConnected never be invoked. I know that IntentService not designed for the binding pattern, but may be there is a common solution for such tasks?

Thanks!

Answer

But when I'm using binding like this onServiceConnected never be invoked

That is because your IntentService is destroyed before the binding request even begins. An IntentService is automatically destroyed when onHandleIntent() completes all outstanding commands.

but may be there is a common solution for such tasks

Don't have two services. Get rid of the IntentService and move its logic into the other service.

Comments