我在启动服务的活动中有一个alarmManager。我想获得我的演示者的一个实例我的服务。我在我的项目中使用了Dagger 2来处理依赖注入。这是我的代码:
我每小时开始/停止服务的活动:
public class ActionsActivity extends ActivityBase {
@Inject
ActionsActivityPresenter mPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_actions);
((App)getApplication()).getMyComponent()
.plus(new ActionsActivityModule()).inject(this);
..........
Intent intent = new Intent(this, EventsService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pendingIntent);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),minuteInMillies * 60, pendingIntent);
........
}
这是我的模块:
@Module(includes = {ContextModule.class, ScannerActivityModule.class})
public class ActionsActivityModule {
.........
@AppScope
@Provides
public RemoveShiftEvent removeShiftEvent(ShiftEventDatabase shiftEventDatabase) {
return new RemoveShiftEventImpla(shiftEventDatabase);
}
@AppScope
@Provides
public ActionsActivityPresenter actionsActivityPresenter(InsertShiftEvent insertShiftEvent, SendShiftEvent sendShiftEvent, RemoveShiftEvent removeShiftEvent, NameEncryptor nameEncryptor) {
return new ActionsActivityPresenter(insertShiftEvent, sendShiftEvent, removeShiftEvent, nameEncryptor);
}
......
}
最后我的服务暂时没有发生任何事情
public class EventsService extends Service {
public EventsService() {
}
private ActionsActivityPresenter actionsActivityPresenter;
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Timber.d( "onStartCommand Service has started");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
我的问题是,有没有办法使用dagger框架在我的服务中注入我的ActionsActivityPresenter?提前谢谢。
答案 0 :(得分:1)
您可以在服务中使用注射器,如活动/片段注射器
@Module(includes = [AndroidSupportInjectionModule::class, ActivityBuilderModule::class, ServiceBuilderModule::classs])
abstract class ApplicationModule
{
@Binds
@Singleton
abstract fun bindApplication(application: BeaverApplication): Application
@Module
companion object
{
@Provides
@Singleton
@ApplicationContext
@JvmStatic
fun provideApplicationContext(application: BeaverApplication): Context = application
}
}
喜欢你"贡献注射器"对于活动/片段,对服务也这样做:
@Module
abstract class ServiceBuilderModule
{
@ContributesAndroidInjector
abstract fun contributeAuthenticatorService(): AuthenticatorService
}
您从我的projet模板here获得了一个具有AuthenticatorService类
的具体示例