java - 如何在 Android fragment 和服务中请求注入(inject)?

标签 java android android-fragments dagger-2

我正在关注 this tutorial将 Dagger 2 添加到我的 Android 项目。

完成设置并创建模块和组件后,我可以像这样在 Activity 中添加依赖项:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_account);
    ButterKnife.bind(this);
    ((AppController) getApplication()).getNetComponent().inject(this);
}

我正在纠结于如何在 Fragment 和 IntentService 中注入(inject)依赖项?

public class FragmentBrandList extends ListFragment {
}

在这个类中,我应该在哪个@Override 方法中请求注入(inject),它的代码是什么?

最佳答案

In this class which @Override method i should use and what will be the code to add dependency in fragment?

在 Fragment 中调用注入(inject)的正确位置是 onAttach(Context context)。这在 Dagger 2 用户指南的注入(inject)位置部分有说明here

@Override
public void onAttach(Context context) {
    ((AppController) context.getApplicationContext()).getNetComponent().inject(this);
    super.onAttach(context);
}

在服务中调用注入(inject)的正确位置是onCreate()

@Override 
public void onCreate() {
    ((AppController) getApplication()).getNetComponent().inject(this);
    super.onCreate();

}

请注意,在这两种情况下,注入(inject)请求都出现在调用 super.onCreate() 之前。 Dagger 用户指南是这样解释的:

It is crucial to call AndroidInjection.inject() before super.onCreate() in an Activity, since the call to super attaches Fragments from the previous activity instance during configuration change, which in turn injects the Fragments. In order for the Fragment injection to succeed, the Activity must already be injected. For users of ErrorProne, it is a compiler error to call AndroidInjection.inject() after super.onCreate().

换句话说:

  1. Activity super.onCreate() 调用重新附加来自先前实例的 fragment
  2. 这个 super 调用导致 fragment 被重新注入(inject)(因为 fragment 是在 onAttach 中注入(inject)的)
  3. Fragments 应该在它们的 Activity 被注入(inject)之后被注入(inject),因此在调用 super.onCreate() 之前请求在你的 Activity 中注入(inject)。

您始终可以通过查看 com.google.dagger:dagger-android 类(如 DaggerFragmentDaggerService)的相关源代码来检查注入(inject)位置。参见 the GitHub repo here

对于您的具体示例,请确保您已将新的注入(inject)站点添加到 NetComponent:

void inject(FragmentBrandList frag);

void inject(BrandListService service);

关于java - 如何在 Android fragment 和服务中请求注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41303896/

相关文章:

java - 如何保护将由 Java 应用程序调用的 AWS API Gateway 终端 Node ?

android - 如何在 android 中编写异步内容提供程序

android - Gradle:有和没有<<运算符的定义任务的区别

android - Google Pay AutoResolveHelper.resolveTask() 没有在 Fragment 中调用 onActivityResult

android - 使用 Koin 和 navArgs 在 childfragment 中获取 sharedviewmodel

java - 为什么我不能在包外使用 protected 构造函数?

java - 电子邮件发送 Python 到 Java 转换

android - Ionic 2 非交互式身份验证

java - 刷新 slider 中的 fragment

java - 等待线程循环完成