Injects core Android types.
| 31 | |
| 32 | /** Injects core Android types. */ |
| 33 | @Beta |
| 34 | public final class AndroidInjection { |
| 35 | private static final String TAG = "dagger.android"; |
| 36 | |
| 37 | /** |
| 38 | * Injects {@code activity} if an associated {@link AndroidInjector} implementation can be found, |
| 39 | * otherwise throws an {@link IllegalArgumentException}. |
| 40 | * |
| 41 | * @throws RuntimeException if the {@link Application} doesn't implement {@link |
| 42 | * HasActivityInjector}. |
| 43 | */ |
| 44 | public static void inject(Activity activity) { |
| 45 | checkNotNull(activity, "activity"); |
| 46 | Application application = activity.getApplication(); |
| 47 | if (!(application instanceof HasActivityInjector)) { |
| 48 | throw new RuntimeException( |
| 49 | String.format( |
| 50 | "%s does not implement %s", |
| 51 | application.getClass().getCanonicalName(), |
| 52 | HasActivityInjector.class.getCanonicalName())); |
| 53 | } |
| 54 | |
| 55 | AndroidInjector<Activity> activityInjector = |
| 56 | ((HasActivityInjector) application).activityInjector(); |
| 57 | checkNotNull(activityInjector, "%s.activityInjector() returned null", application.getClass()); |
| 58 | |
| 59 | activityInjector.inject(activity); |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * Injects {@code fragment} if an associated {@link AndroidInjector} implementation can be found, |
| 64 | * otherwise throws an {@link IllegalArgumentException}. |
| 65 | * |
| 66 | * <p>Uses the following algorithm to find the appropriate {@code AndroidInjector<Fragment>} to |
| 67 | * use to inject {@code fragment}: |
| 68 | * |
| 69 | * <ol> |
| 70 | * <li>Walks the parent-fragment hierarchy to find the a fragment that implements {@link |
| 71 | * HasFragmentInjector}, and if none do |
| 72 | * <li>Uses the {@code fragment}'s {@link Fragment#getActivity() activity} if it implements |
| 73 | * {@link HasFragmentInjector}, and if not |
| 74 | * <li>Uses the {@link android.app.Application} if it implements {@link HasFragmentInjector}. |
| 75 | * </ol> |
| 76 | * |
| 77 | * If none of them implement {@link HasFragmentInjector}, a {@link IllegalArgumentException} is |
| 78 | * thrown. |
| 79 | * |
| 80 | * @throws IllegalArgumentException if no parent fragment, activity, or application implements |
| 81 | * {@link HasFragmentInjector}. |
| 82 | */ |
| 83 | public static void inject(Fragment fragment) { |
| 84 | checkNotNull(fragment, "fragment"); |
| 85 | HasFragmentInjector hasFragmentInjector = findHasFragmentInjector(fragment); |
| 86 | if (Log.isLoggable(TAG, DEBUG)) { |
| 87 | Log.d( |
| 88 | TAG, |
| 89 | String.format( |
| 90 | "An injector for %s was found in %s", |
nothing calls this directly
no outgoing calls
no test coverage detected