I want to use dagger approach to for helper classes. Bellow is the code i am currently using for Activity. But i am not able to understand how should i be using this for helper class.
Where helper class is called inside a receiver.
AppComponent.java
@Singleton
@Component(modules = { AndroidSupportInjectionModule.class, AppModule.class, ActivityBuilder.class})
public interface AppComponent extends AndroidInjector<DaggerApplication> {
void inject(MyApplication app);
@Override
void inject(DaggerApplication instance);
@Component.Builder
interface Builder {
@BindsInstance
Builder application(Application application);
AppComponent build();
}
}
ActivityBuilder.java
@Module
public abstract class ActivityBuilder {
@ContributesAndroidInjector(modules = MainActivityModule.class)
abstract MainActivity bindMainActivity();
}
AppModule.java
@Module
public abstract class AppModule {
@Binds
abstract Context provideContext(Application application);
}
MainActivityModule.java
@Module
public abstract class MainActivityModule {
@Provides
static MainPresenter provideMainPresenter(MainView mainView) {
return new MainPresenterImpl(mainView);
}
@Binds
abstract MainView provideMainView(MainActivity mainActivity);
}
The above code is what i am using for activities. I am now willing to use same structure for my helper classes too. I did a plenty of research and tried some methods which were failing as my Helper class requires 2 parameter. First one is context and another is IPhoneCallReceiver. I know IPhoneCallReceiver can be accessed in @Module
using @Binds
, but i am having issue getting Context. Here Helper class is CallStateHelper
PhoneCallReceiver.java
public class PhoneCallReceiver extends BroadcastReceiver implements IPhoneCallReceiver {
CallStateHelper callStateHelper;
@Override
public void onReceive(Context context, Intent intent) {
callStateHelper.stateChange(intent);
}
}
CallStateHelper.java
public class CallStateHelper extends PhoneStateListener {
private IPhoneCallReceiver receiver;
public CallStateHelper(Context context, IPhoneCallReceiver receiver) {
this.receiver = receiver;
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(this, PhoneStateListener.LISTEN_CALL_STATE);
}
@Override
public void onCallStateChanged(int state, String incomingNumber) {
}
}
I want to use CallStateHelper by @Inject
and want it as Singleton
Class. I am very new to Dagger
I finally did it.
You just have to provide DispatchingAndroidInjector<BroadcastReceiver>