An Application that injects its members and can be used to inject Activitys, Fragments, Services, BroadcastReceivers and ContentProviders attached to it. Injection is performed in #onCreate() or the first call to {@link AndroidInjection#inject(
| 33 | * AndroidInjection#inject(ContentProvider)}, whichever happens first. |
| 34 | */ |
| 35 | @Beta |
| 36 | public abstract class DaggerApplication extends Application |
| 37 | implements HasActivityInjector, |
| 38 | HasFragmentInjector, |
| 39 | HasServiceInjector, |
| 40 | HasBroadcastReceiverInjector, |
| 41 | HasContentProviderInjector { |
| 42 | |
| 43 | @Inject DispatchingAndroidInjector<Activity> activityInjector; |
| 44 | @Inject DispatchingAndroidInjector<BroadcastReceiver> broadcastReceiverInjector; |
| 45 | @Inject DispatchingAndroidInjector<Fragment> fragmentInjector; |
| 46 | @Inject DispatchingAndroidInjector<Service> serviceInjector; |
| 47 | @Inject DispatchingAndroidInjector<ContentProvider> contentProviderInjector; |
| 48 | private volatile boolean needToInject = true; |
| 49 | |
| 50 | @Override |
| 51 | public void onCreate() { |
| 52 | super.onCreate(); |
| 53 | injectIfNecessary(); |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * Implementations should return an {@link AndroidInjector} for the concrete {@link |
| 58 | * DaggerApplication}. Typically, that injector is a {@link dagger.Component}. |
| 59 | */ |
| 60 | @ForOverride |
| 61 | protected abstract AndroidInjector<? extends DaggerApplication> applicationInjector(); |
| 62 | |
| 63 | /** |
| 64 | * Lazily injects the {@link DaggerApplication}'s members. Injection cannot be performed in {@link |
| 65 | * Application#onCreate()} since {@link android.content.ContentProvider}s' {@link |
| 66 | * android.content.ContentProvider#onCreate() onCreate()} method will be called first and might |
| 67 | * need injected members on the application. Injection is not performed in the constructor, as |
| 68 | * that may result in members-injection methods being called before the constructor has completed, |
| 69 | * allowing for a partially-constructed instance to escape. |
| 70 | */ |
| 71 | private void injectIfNecessary() { |
| 72 | if (needToInject) { |
| 73 | synchronized (this) { |
| 74 | if (needToInject) { |
| 75 | @SuppressWarnings("unchecked") |
| 76 | AndroidInjector<DaggerApplication> applicationInjector = |
| 77 | (AndroidInjector<DaggerApplication>) applicationInjector(); |
| 78 | applicationInjector.inject(this); |
| 79 | if (needToInject) { |
| 80 | throw new IllegalStateException( |
| 81 | "The AndroidInjector returned from applicationInjector() did not inject the " |
| 82 | + "DaggerApplication"); |
| 83 | } |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | @Inject |
| 90 | void setInjected() { |
| 91 | needToInject = false; |
| 92 | } |
nothing calls this directly
no outgoing calls
no test coverage detected