作者:一号小蘑菇妖 | 来源:互联网 | 2023-02-09 15:37
提供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;
}
}
这是我要注入改造的片段。
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中,改造实例均为null。