简体   繁体   中英

How to inject a bound service into an Activity via dagger?

I would like to inject a bound service into my activity via Dagger2.

My Service is declared as follow:

Public class MyService extends Service{
private final IBinder mBinder = new LocalBinder();
...
public class LocalBinder extends Binder {
    public MyService getService() {
        return MyService.this;
    }
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

public void doBackgroundTask() {
...
}

}

My Activity:

public abstract class MainActivity extends AppCompatActivity {

@Inject
MyService service;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
service.doBackgroundTask();
...
}

How would you achieve that ? Where will you put the ServiceConnection (into a base class, inside the module) ?

Thanks a lot.

I don't think that injecting the service that way (via injected field) will work because you don't control the instantiation of the service's object.

If your service contains fields that need to be injected you will have to inject in onCreate() the same way you inject your activities, ie calling DaggerMyAppComponent.inject(this) .

About the ServiceConnection: you will have to do it the usual way as described in http://developer.android.com/guide/components/bound-services.html

I was dealing with the same concept/problem and like @Ognyan says - you won't have control over creating service.

I think this: How to access service functions from fragment, which is bound to parent activity in Android? might help you.

You may instantiate service in Application/Activity and communicate with it as described in the attached link.

You may also think of putting the interface (which is communicating with service) in base abstract class (BaseActivity or BaseFragment) which Fragment/Activity inherits and then easily reach the interface in any fragment or activity you need.

Hope it solves your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM