Android dagger的使用

embedded/2024/11/15 1:41:42/

官方讲解:https://developer.android.google.cn/training/dependency-injection/dagger-basics?hl=zh_cn
Google demo:https://github.com/android/architecture-samples

添加依赖库

	//dagger2implementation 'com.google.dagger:dagger:2.35'annotationProcessor 'com.google.dagger:dagger-compiler:2.35'// retrofit2implementation 'com.squareup.retrofit2:retrofit:2.3.0'implementation 'com.squareup.retrofit2:converter-gson:2.3.0'implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'// okhttp3implementation 'com.squareup.okhttp3:okhttp:3.8.0'// log拦截器implementation 'com.squareup.okhttp3:logging-interceptor:3.8.0'// cookie管理implementation 'com.github.franmontiel:PersistentCookieJar:v1.0.1'

创建实例提供者

Api

@Module
public class ApiModule {@Provides@Singletonpublic ServiceApi provideServiceApi(Retrofit retrofit) {return retrofit.create(ServiceApi.class);}@Provides@Singletonpublic Retrofit getRetrofit(OkHttpClient okHttpClient) {Gson gson = new GsonBuilder()
//                .setDateFormat("yyyy-MM-dd HH:mm:ss").registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {@Overridepublic Date deserialize(JsonElement element, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {String date = element.getAsString();SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");format.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));try {Date date1 = format.parse(date);return date1;} catch (ParseException exp) {exp.printStackTrace();return null;}}}).create();return new Retrofit.Builder()// 集成RxJava处理.addCallAdapterFactory(RxJava2CallAdapterFactory.create())// 集成Gson转换器.addConverterFactory(GsonConverterFactory.create(gson))// 使用OkHttp Client.client(okHttpClient)// baseUrl总是以/结束,@URL不要以/开头.baseUrl(AppConfig.API_SERVER_URL).build();}@Provides@Singletonpublic OkHttpClient okHttpClient(Cache cache, App application) {HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();loggingInterceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);ClearableCookieJar cookieJar =new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(application.getApplicationContext()));return new OkHttpClient.Builder().addInterceptor(authTokenInterceptor()).addInterceptor(loggingInterceptor) // 添加日志拦截器.addInterceptor(buildCacheInterceptor()).cache(cache) // 设置缓存文件.retryOnConnectionFailure(true) // 自动重连.connectTimeout(15, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS).cookieJar(cookieJar).build();}@Provides@Singletonpublic Cache getCache(App application) {File cacheFile = new File(application.getCacheDir(), "networkCache");// 创建缓存对象,最大缓存50mreturn new Cache(cacheFile, 1024 * 1024 * 50);}private Interceptor authTokenInterceptor() {return chain -> {Request request = chain.request();TimeZone timeZone = TimeZone.getDefault();timeZone.setID("");String tz2 = timeZone.getDisplayName(true, TimeZone.SHORT);Request authRequest = request.newBuilder().header("timeZone", tz2).build();return chain.proceed(authRequest);};}private Interceptor buildCacheInterceptor() {return chain -> {Request request = chain.request();// 无网络连接时请求从缓存中读取if (!NetworkUtils.isConnected()) {request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();}// 响应内容处理:在线时缓存5分钟;离线时缓存4周Response response = chain.proceed(request);if (NetworkUtils.isConnected()) {int maxAge = 300;response.newBuilder().header("Cache-Control", "public, max-age=" + maxAge).removeHeader("Pragma") // 清除头信息,因为服务器如果不支持,会返回一些干扰信息,不清除下面无法生效.build();} else {// 无网络时,设置超时为4周int maxStale = 60 * 60 * 24 * 28;response.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).removeHeader("Pragma").build();}return response;};}}
  • 根据需要创建其他实例提供者,比如OSS或者App
@Module
public class OSSModule {@Provides@SingletonOSS provideOss(App app, ServiceApi api) {final String[] endpoints = {"https://oss-cn-xxxxx.aliyuncs.com"};OSSCustomSignerCredentialProvider provider = new OSSCustomSignerCredentialProvider() {@Overridepublic String signContent(String content) {String sign = null;return sign;}};ClientConfiguration conf = new ClientConfiguration();conf.setConnectionTimeout(15 * 1000); // 连接超时,默认15秒conf.setSocketTimeout(15 * 1000); // socket超时,默认15秒conf.setMaxConcurrentRequest(5); // 最大并发请求书,默认5个conf.setMaxErrorRetry(3); // 失败后最大重试次数,默认2次return new OSSClient(app, endpoints[0], provider, conf);}
}@Module
public class ApplicationModule {private App mApplication;public ApplicationModule(App application) {mApplication = application;}@Provides@SingletonApp provideApplication() {return mApplication;}@Provides@ApplicationContext@SingletonContext provideContext() {return mApplication;}
}
  • 组合的实例提供者
@Singleton
@Component(modules = {ApplicationModule.class,ApiModule.class,OSSModule.class
})
public interface ApplicationComponent {@ApplicationContextContext context();App application();ServiceApi serviceApi();OSS oss();OkHttpClient okHttpClicent();
}
  • 可选项,限定符
@Qualifier
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface ApplicationContext {
}
  • 可选项,使用范围
@Documented
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface PerActivity {
}@Documented
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface PerFragment {
}@Documented
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface PerService {
}

创建注入器

每用一个,都要在这里加一个注入接口

@PerActivity
@Component(dependencies = {ApplicationComponent.class})
public interface ActivityComponent {void inject(MainActivity mainActivity);
}@PerFragment
@Component(dependencies = {ApplicationComponent.class})
public interface FragmentComponent {void inject(HomeFragment homeFragment);
}

注入

可在基类中封装,也可以单独在每个界面注入

public class App extends Application{private ApplicationComponent mApplicationComponent;public ApplicationComponent getApplicationComponent() {if (mApplicationComponent == null) {mApplicationComponent = DaggerApplicationComponent.builder().applicationModule(new ApplicationModule(this)).apiModule(new ApiModule()).oSSModule(new OSSModule()).build();}return mApplicationComponent;}
}基类封装private ActivityComponent mActivityComponent;public ActivityComponent getActivityComponent() {if (mActivityComponent == null) {mActivityComponent = DaggerActivityComponent.builder().applicationComponent(App.getApp().getApplicationComponent()).build();}return mActivityComponent;}@Override@CallSuperprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);inject(getActivityComponent());}protected void inject(ActivityComponent activityComponent) {// 子类具体实现dagger注入}子类具体注入@Overrideprotected void inject(ActivityComponent activityComponent) {activityComponent.inject(this);}

结合mvp

  • 基类
// 基类Activity
public abstract class BaseActivity<P extends BaseActivityPresenter>{@Injectprotected P mPresenter;@Override@CallSuperprotected void onCreate(@Nullable Bundle savedInstanceState) {if (mPresenter != null) {mPresenter.attachView(this);}}@Override@CallSuperprotected void onDestroy() {if (mPresenter != null) {mPresenter.detachView();}}
}// 基类Presenter
public abstract class BaseActivityPresenter<T extends BaseActivity> {protected T mActivity;public void attachView(T activity) {mActivity = activity;}public void detachView() {if (mActivity != null) {mActivity = null;}}
}
  • 子类
public class MainActivity extends BaseActivity<MainPresenter> {mPresenter.xxxApi()private onXxxApiOk(){}}public class MainPresenter extends BaseActivityPresenter<MainActivity> {private ServiceApi mApi;@Injectpublic MainPresenter(ServiceApi api) {mApi = api;}public void xxxApi(String xxxId) {mApi.xxxxxxx(xxxId).xxx// rxjava 和 retrofit那一套.subscribe(new RxSubscriber<BaseHttpEntity<XXXEntity>>() {@Overrideprotected void onSuccess(BaseHttpEntity<XXXEntity> response) {mActivity.onXxxApiOk(response.getDetails());}});}}   

http://www.ppmy.cn/embedded/137637.html

相关文章

git config是做什么的?

git config是做什么的&#xff1f; git config作用配置级别三种配置级别的介绍及使用&#xff0c;配置文件说明 使用说明git confi查看参数 默认/不使用这个参数 情况下 Git 使用哪个配置等级&#xff1f; 一些常见的行为查看配置信息设置配置信息删除配置信息 一些常用的配置信…

UE5材质篇 2 ICE 冰材质尝试

冰的特色是表面有划痕&#xff0c;看下去有折射感 于是我找素材 https://www.fab.com/listings/f0ec263b-992c-4e96-b27e-86934684af6c 另外的划痕也是那里下载的frozen lake 材质不让他真透明&#xff0c;用SSS 第一个视差&#xff0c;对diffuse roughtness normal都要应…

如何有效进行谷歌SEO外链建设?

很多人关心如何才能更有效地发布谷歌SEO外链。在这方面&#xff0c;保证外链的收录是最重要的。不管你在多么高权重的平台上发布外链&#xff0c;如果没有被收录&#xff0c;那都是徒劳。所以&#xff0c;提高收录率的关键之一就是通过数量来提升概率——多发外链&#xff0c;才…

jmeter常用配置元件介绍总结之用linux服务器压测

系列文章目录 安装jmeter jmeter常用配置元件介绍总结之用linux服务器压测 1.编写测试脚本2.执行测试脚本 1.编写测试脚本 在linux服务器上进行压测&#xff0c;由于是没有界面的&#xff0c;因此我们可以先在界面上把压测脚本写好&#xff1a; 如图&#xff1a;我这里简单的写…

编程之路,从0开始:知识补充篇

Hello大家好&#xff0c;很高兴我们又见面了&#xff01; 给生活添点passion&#xff0c;开始今天的编程之路&#xff01; 这一篇我们来补充一下在之前篇目没讲到的知识&#xff0c;并结合一些码友的私信提问和我在编程中遇到的问题&#xff0c;做一些易错点或易混点的讲解。 …

面试题:进程间通信和Binder相关

1、android中进程间通信有几种方法&#xff1f; 答&#xff1a;共享内存&#xff0c;管道&#xff0c;Socket&#xff0c;文件操作&#xff0c;Binder&#xff08;Messenger&#xff0c; Bundle&#xff0c; AIDL&#xff09; 2、在AIDL中的oneway关键字是起到什么作用&#x…

卫导调零天线功率倒置算法原理及MATLAB仿真

卫导调零天线功率倒置算法原理及MATLAB仿真 文章目录 前言一、调零天线简介二、功率倒置自适应算法三、MATLAB仿真四、MATLAB代码总结 前言 \;\;\;\;\; 自适应调零抗干扰技术可以很大程度改善导航抗干扰性能&#xff0c;也是目前导航抗干扰技术中不可或缺的&#xff0c;其研究意…

⚙️ 如何调整重试策略以适应不同的业务需求?

调整 Kafka 生产者和消费者的重试策略以适应不同的业务需求&#xff0c;需要根据业务的特性和容错要求来进行细致的配置。以下是一些关键的调整策略&#xff1a; 业务重要性&#xff1a; 对于关键业务消息&#xff0c;可以增加重试次数&#xff0c;并设置较长的重试间隔&#x…