1 /*
2  * Copyright (C) 2020 The Dagger Authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package dagger.hilt.android;
18 
19 import android.app.Activity;
20 import android.content.Context;
21 import androidx.fragment.app.Fragment;
22 import android.view.View;
23 import dagger.hilt.EntryPoints;
24 import javax.annotation.Nonnull;
25 
26 /** Static utility methods for dealing with entry points for standard Android components. */
27 public final class EntryPointAccessors {
28 
29   /**
30    * Returns the entry point interface from an application. The context can be any context derived
31    * from the application context. May only be used with entry point interfaces installed in the
32    * ApplicationComponent.
33    */
34   @Nonnull
fromApplication(Context context, Class<T> entryPoint)35   public static <T> T fromApplication(Context context, Class<T> entryPoint) {
36     return EntryPoints.get(context.getApplicationContext(), entryPoint);
37   }
38 
39   /**
40    * Returns the entry point interface from an activity. May only be used with entry point
41    * interfaces installed in the ActivityComponent.
42    */
43   @Nonnull
fromActivity(Activity activity, Class<T> entryPoint)44   public static <T> T fromActivity(Activity activity, Class<T> entryPoint) {
45     return EntryPoints.get(activity, entryPoint);
46   }
47 
48   /**
49    * Returns the entry point interface from a fragment. May only be used with entry point interfaces
50    * installed in the FragmentComponent.
51    */
52   @Nonnull
fromFragment(Fragment fragment, Class<T> entryPoint)53   public static <T> T fromFragment(Fragment fragment, Class<T> entryPoint) {
54     return EntryPoints.get(fragment, entryPoint);
55   }
56 
57   /**
58    * Returns the entry point interface from a view. May only be used with entry point interfaces
59    * installed in the ViewComponent or ViewNoFragmentComponent.
60    */
61   @Nonnull
fromView(View view, Class<T> entryPoint)62   public static <T> T fromView(View view, Class<T> entryPoint) {
63     return EntryPoints.get(view, entryPoint);
64   }
65 
EntryPointAccessors()66   private EntryPointAccessors() {}
67 }
68