使用Dagger 2投入服务 [英] Using Dagger 2 to inject into service

查看:76
本文介绍了使用Dagger 2投入服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,该应用程序基本上是一项始终运行的服务,并在发生某些情况时向用户发出警报.

I have an app which is basically a service that runs all the time and alarms the user when something happens.

服务创建警报时,需要为其提供context,以便警报可以在发生事件时对服务进行回调.

When the service creates the alarm, it needs to give it his context so that the alarm can do callbacks to the service when something happens.

例如:

public MyService extends Service{
    private SomeAlarm alarm;

    @Override
    public void onCreate() {
        super.onCreate();
        alarm = new SomeAlarm(MyService.this);
    }
}

如何将SomeAlarm类注入服务,并将SomeAlarm服务上下文作为变量提供?

How can I inject the SomeAlarm class into the service, and give the SomeAlarm the service context as a variable?

推荐答案

我从头顶写了代码,所以可能会有一两个错字.

I wrote the code from the top of my head, so there could be a typo or two.

您执行的操作与向活动中注入内容时的操作相同.

You do it just the same as when injecting stuff into activities.

  1. 声明组件,
  2. 将inject方法添加到该组件,
  3. 添加一个提供您服务的模块
  4. 创建该组件构建器
  5. 将模块添加到构建器
  6. 使用组件注入服务

您的模块和组件看起来像这样(也许添加一些作用域)

Your module and component would look something like this (maybe add some scope)

@Module
class ServiceModule {

    MyService mService;

    ServiceModule(MyService service) {
        mService = service;
    }

    @Provides
    MyService provideMyService() {
        return mService;
    }
}

@Component(modules=ServiceModule.class)
interface MyServiceComponent {
    void inject(MyService service);
}

然后在onCreate中仅创建您的组件并注入警报.

Then in onCreate just create your component and inject your alarm.

@Inject
private SomeAlarm alarm;

public void onCreate() {
    DaggerMyServiceComponent.builder()
            .serviceModule(new ServiceModule(this))
            .build()
            .inject(this);

    alarm.doStuff();
}

这是假设您的警报可以通过具有@Inject注释的构造函数来注入,例如:

This is assuming that your alarm can be constructor injected by having an @Inject annotated constructor like this:

class SomeAlarm {
    @Inject
    SomeAlarm(MyService service) {
        /*constructor stuff*/
    }
}

否则,您也只需将警报创建添加到模块中即可.

Else you would just also add the alarm creation to your module.

这篇关于使用Dagger 2投入服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆