How do I start a service from my Interactor using

2019-03-19 08:15发布

问题:

I'm following the Model View Presenter (MVP) pattern similar to Antonio Leiva's example found here: antoniolg/github.

I've been playing around with it quite a bit and I was wondering how I would start a service from the interactor layer. Normally I've been putting my retrofit calls inside the interactor but I was wondering if there is a way to start a service from the interactor so I could run my retrofit calls in the service instead. Problem here is that I don't have the activity context to run the service and it kind of defeats the purpose of the MVP if I were to expose the context to the interactor.

I'm also not quite sure if this is even a good thing to be doing (starting services from the interactor). I was thinking about starting services from the presenter layer instead, but I'm running towards dead ends on how I should be approaching this.

If there's a way around this, please help a fellow out? Or enlighten me if this is not a good approach.

回答1:

Define class for example My App extends Application and define method like getAppInstance returns Application object and then add name attribute of this class to Applicqtion Tag in Manifest then call this method inside your use case to get context object and start your service

public class MyApp extends Application {

private MyApp instance;

@Override
public void onCreate() {
    super.onCreate();

    instance = this;

}

@Override
public void onTerminate() {
    super.onTerminate();

    instance = null;
}

public MyApp getInstance(){
    return  instance;

}

}