【发布时间】:2017-03-09 05:48:00
【问题描述】:
提供Gson、Retrofit和OkHttpClient单例的模块
@Module
public class MyModule {
@Provides
@Singleton
Gson provideGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
return gsonBuilder.create();
}
@Provides
@Singleton
OkHttpClient provideOkHttpClient() {
OkHttpClient client = new OkHttpClient();
return client;
}
@Provides
@Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(BuildConfig.SERVER_BASE_URL)
.client(okHttpClient)
.build();
return retrofit;
}
}
允许将单例注入活动和片段的组件
@Singleton
@Component(modules={MyModule.class})
public interface MyComponent {
void inject(Activity activity);
void inject(Fragment fragment);
void inject(Application application);
}
构建组件的主应用程序类
public class MyApp extends Application{
private MyComponent component;
@Inject
Retrofit retrofit;
@Override
public void onCreate() {
super.onCreate();
component= DaggerMyComponent.builder()
.myModule(new MyModule()).build();
getComponent().inject(this); // inject retrofit here
}
public MyComponent getComponent() {
return component;
}
}
这是我尝试注入 Retrofit 的片段。
public class MyFragment extends Fragment {
@Inject
Retrofit retrofit;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
((MyApp)getActivity().getApplication()).getComponent().inject(this);
....
}
}
在 MyApp 和 MyFragment 中,改造实例均为空。
【问题讨论】:
-
我觉得不错。
-
我也是这么想的,但它没有注入 Retrofit :(
-
@Coder 找到解决方案了吗?
标签: android retrofit2 dagger-2