gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 19:52:58 24 4
gpt4 key购买 nike

我正在关注 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com