How To Inject The Creation Of A Broadcastreceiver Object In Fragment Using Dagger2?
Solution 1:
The problem is that Dagger2 cannot do magic. How it should know from where to provide a OnNetCallback. Your fragment extends this callback but neither its constructor is annotated with @Inject annotation(because you are not advised to create explicit fragment constructors) nor it is provided with @Provides annotated method in your module, nor OnNetCallback is bind with MapFragment via @Bind annotated method which is a "must be" when you trying to inject interface like this along with a @Qualifier.
But that is not the main issue.
Even if you will manage to do all the previous stuff correctly it will still not work because there will be a circular dependency - MapFragment depends on NetReceiver, NetReceiver depends on OnNetCallback, OnNetCallback is a MapFragment, thus NetReceiver depends on MapFragment. Dagger won't let you do it.
If you want your MapFragment to implement OnNetCallback I would suggest something like:
publicclassNetReceiverextendsBroadcastReceiver {
publicOnNetCallback onNetCallback;
@OverridepublicvoidonReceive(Context context, Intent intent) {
if (someCondition && onNetCallback!= null) {
onNetCallback.enableOperation(true);
}
}
publicinterfaceOnNetCallback {
voidenableOperation(boolean isOk);
}
}
publicclassMapFragmentextendsDaggerFragmentimplementsNetReceiver.OnNetCallback {
@InjectNetReceiver netReceiver;
@OverridepublicViewonCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflate View
netReceiver.onNetCallback = this
}
@OverridepublicvoidonResume() {
super.onResume();
mainActivity.registerReceiver(netReceiver, intentFilter);
}
@OverridepublicvoidonPause() {
super.onPause();
mainActivity.unregisterReceiver(netReceiver);
}
}
If you want it to be injected - create some separate from Fragment implementation of OnNetCallback and @Provide it in module and inject it into fragment.
Also @ContributesAndroidInjector should be used for the injeters but not for the injectees - it tells Dagger that this class should be injected with some stuff described with @Inject, @Provides and @Bind annotations.
Also I would recommend you to read an official guide regarding Dagger2 and its usage for Android.
Hope it helps.
Post a Comment for "How To Inject The Creation Of A Broadcastreceiver Object In Fragment Using Dagger2?"