简体   繁体   English

如何使用 android 中的 MVP 模式从我的交互器启动服务?

[英]How do I start a service from my Interactor using the MVP pattern in android?

I'm following the Model View Presenter (MVP) pattern similar to Antonio Leiva's example found here: antoniolg/github .我正在遵循类似于 Antonio Leiva 在此处找到的示例的模型视图演示者 (MVP) 模式: 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.我一直在玩它,我想知道如何从interactor层启动service 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.通常我一直将retrofit调用放在interactor但我想知道是否有办法从interactor启动服务,以便我可以在服务中运行我的retrofit调用。 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 .这里的问题是我没有活动上下文来运行服务,如果我将上下文公开给interactor ,这有点违背了 MVP 的目的。

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.我正在考虑从presenter层启动服务,但我正在走向死胡同,我应该如何解决这个问题。

If there's a way around this, please help a fellow out?如果有办法解决这个问题,请帮助一个人? Or enlighten me if this is not a good approach.如果这不是一个好方法,请启发我。

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定义类,例如我的应用程序扩展应用程序并定义方法,如 getAppInstance 返回应用程序对象,然后将此类的名称属性添加到清单中的 Applicqtion 标签,然后在您的用例中调用此方法以获取上下文对象并启动您的服务

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;

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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