我在启动服务的活动中有一个警报管理器。我想获取演示者我的服务的实例。我在我的项目中使用了 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?提前谢谢你。
您可以在服务中使用注入器,例如活动/片段注入器
@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
}
您从我的项目模板中得到了一个具体示例,其中包含身份验证器服务类