android - Dagger 2不会注入特定服务

时间:2016-05-07 12:32:48

标签: java android dependency-injection inversion-of-control dagger-2

我想将SharedPPrefrences对象注入不同的服务和活动。我有这段代码:

申请模块:

@Module
public class ApplicationModule {
    private Application mApp;
    public ApplicationModule(Application app) {
        mApp = app;
    }

    @Provides
    @Singleton
    SharedPreferences provideSharedPrefs() {
        return PreferenceManager.getDefaultSharedPreferences(mApp);
    }
}

应用程序组件:

@Singleton
@Component(modules = {ApplicationModule.class})
public interface ApplicationComponent {
    void inject(HealthCheckerApplication app);
    void inject(HomeActivity activity);
    void inject(Service activity);
    void inject(TestService activity);
    void inject(HealthService activity);
}

由于一些奇怪的原因,编译器给我一个关于HealthService的编译错误 -

  

如果没有@Inject构造函数或者,则无法提供HealthService   来自@ Provide-annotated方法。此类型支持成员   注射但不能隐含提供。

我无法理解我的生活中服务之间的区别是什么。

测试服务:

public class TestService extends Service  {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

健康服务:

public class HealthService extends Service {

    @Inject
    public NotificationCreator notificationCreator;

    @Inject
    public CallTooLongAlarm callTooLongAlarm;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        showToast("onCreate");
        ServiceComponent serviceComponent = DaggerServiceComponent.builder().serviceModule(new ServiceModule(this)).build();
        serviceComponent.injectService(this);

        notificationDataFactory = serviceComponent.provideFactory();
    }
}

唯一的区别是 - 我有ServiceModuleServiceComponent帮助HealthService将自己注入CallTooLongAlarm的构造函数中,例如,但为什么这是一个问题??

0 个答案:

没有答案