Dagger2+Rxjava2+Retrofit+MVP小案例

1. 添加依赖

    1. 在Project的 build.gradle文件添加

    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    classpath 'me.tatarka:gradle-retrolambda:3.2.4'

    2. 在App下的build.gradle添加

    头部添加
    apply plugin: 'com.neenbedankt.android-apt'
    apply plugin: 'me.tatarka.retrolambda'

    3. android{}中添加

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    4. dependencies {}中添加

    dagger相关

    apt 'com.google.dagger:dagger-compiler:2.2'
    compile 'com.google.dagger:dagger:2.2'
    provided 'org.glassfish:javax.annotation:10.0-b28'

    rxjava retrofit相关

    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
    compile 'io.reactivex.rxjava2:rxjava:2.0.1'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'com.squareup.okhttp3:logging-interceptor:3.6.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'

2. 配置单例对象

    1. 创建ActivityScope 该类用于区分与@Sigleton或其他@Scope的作用域。
    @Scope
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ActivityScope {
    }

    2. 创建Module
        2.1 创建AppModule 提供SharedPreferences和Context对象

            @Module
            public class AppModule {

                private Context context;
                public AppModule(MyApplication application){
                    this.context = application;
                }

                @Singleton
                @Provides
                public Context getApplication() {
                    return context;
                }

                @Singleton
                @Provides
                @Named("default")
                public SharedPreferences getSharedPreferences(){
                    return PreferenceManager.getDefaultSharedPreferences(context);
                }

                @Singleton
                @Provides
                @Named("config")
                public SharedPreferences getConfigGetSharedPreferences(){
                    return context.getSharedPreferences("config",Context.MODE_PRIVATE);
                }
            }

        2.2 因为网络框架是Rxjava+Retrofit 所以要提供OkHttpModule,RetrofitModule两个类

            1. 创建OkHttpModule

            @Module
            public class OkHttpModule {

                /**
                 * 缓存文件大小
                 */
                private static long maxSize = 8 * 1024 * 1024;
                /**
                 * 超时时间
                 */
                private final  static  long TIMEOUT = 500;
                private Cache mCache;
                private static File cacheFile;
                private OkHttpClient okHttpClient;

                @Singleton
                @Provides
                @Named("cache")
                public OkHttpClient provideOkHttpClient(){
                    if(mCache == null) {
                        cacheFile = new File(MyApplication.getApplication().getCacheDir().getAbsolutePath(), "cache_mvp");
                        mCache = new Cache(cacheFile, maxSize);
                    }
                    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(message -> Log.e("OkHttpModule",message));
                    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                    if(okHttpClient == null) {
                        okHttpClient = new OkHttpClient.Builder()
                                .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                                .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                                .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                                .addInterceptor(loggingInterceptor)
                                //设置缓存
                                .cache(mCache)
                                .build();
                    }
                    return okHttpClient;
                }

            }


            2. 创建RetrofitModule

            @Module
            public class RetrofitModule {

                @Singleton
                @Provides
                public Retrofit provideRetrofit(@Named("cache") OkHttpClient okHttpClient){
                    return RetrofitHelper.getInstance(okHttpClient).getRetrofit();
                }

                @Singleton
                @Provides
                public RetrofitService provideRetrofitService(Retrofit retrofit){
                    return retrofit.create(RetrofitService.class);
                }
            }

            3. 提供一个获取Retrofit单例对象的帮助类

            public class RetrofitHelper {

                private static final String BASE_URL = "http://ip.taobao.com/";
                private Retrofit mRetrofit;
                private static RetrofitHelper helper;

                private RetrofitHelper(OkHttpClient okHttpClient){

                    mRetrofit = new Retrofit.Builder()
                            .baseUrl(BASE_URL)
                            //添加Gson支持
                            .addConverterFactory(GsonConverterFactory.create())
                            //添加RxJava支持
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            //关联OkHttp
                            .client(okHttpClient)
                            .build();
                }

                /**
                 *单例 保证对象唯一
                 */
                public static RetrofitHelper getInstance(OkHttpClient okHttpClient){
                    if(helper == null) {
                        synchronized (RetrofitHelper.class){
                            if(helper == null){
                                helper = new RetrofitHelper(okHttpClient);
                            }
                        }
                    }
                    return helper;
                }

                /**
                 * 获取Retrofit对象
                 * @return
                 */
                public Retrofit getRetrofit(){
                    return mRetrofit;
                }

            }

3. 创建AppConponent

    /**
     * 通过modules把需要的Module全部添加进来
     */
    @Singleton
    @Component(modules = {AppModule.class,OkHttpModule.class,RetrofitModule.class})
    public interface AppComponent {
        /**
         * 添加MainComponent
         * @param mainModule
         * @return
         */
        MainComponent addSub(MainModule mainModule);
    }

4. 自定义Application

    public class MyApplication extends Application {

        private static MyApplication mContext;
        private static AppComponent appComponent;

        @Override
        public void onCreate() {
            super.onCreate();

            mContext = this;

            appComponent = DaggerAppComponent.builder()
                                            .appModule(new AppModule(this))
                                            .build();
        }

        public static MyApplication getApplication() {
            return mContext;
        }

        public static AppComponent getAppComponent() {
            return appComponent;
        }
    }

5.网络工具类封装

    1. 封装Observer

    public abstract class BaseObserver<T extends BaseInfo> implements Observer<T>{

        protected IBaseView mView;
        private final String TAG;
        private Disposable mDisposable;
        public BaseObserver(IBaseView view){
            this.mView = view;
            TAG = getClass().getSimpleName();
        }

        @Override
        public void onSubscribe(Disposable d) {
            this.mDisposable = d;
            if(mView!=null) {
                mView.addRxDisposable(d);
            }
        }

        @Override
        public void onNext(T t) {
            this.onSuccess(t);
        }

        @Override
        public void onError(Throwable e) {
            this.onError(e,e.getMessage());
            if(mDisposable !=null) {
                mDisposable.dispose();
            }
            if(mView != null) {
                mView.onError(e.getMessage());
            }
        }

        @Override
        public void onComplete() {
            Log.e(TAG +" : onComplete","请求成功");
            if(mView != null){
                mView.closeLoading();
            }else if(mDisposable!=null){
                mDisposable.dispose();
            }
        }

        /**
         * 请求成功
         * @param t
         */
        public abstract void onSuccess(T t);

        /**
         * 请求错误
         * @param e
         * @param msg
         */
        public abstract void onError(Throwable e,String msg);
    }

    2. 网络工具类封装

    public class HttpUtil {

        /**
         *Post方式请求网络 mvp方式 传view
         */
        public static <T extends BaseInfo> void post(Observable observable, IBaseView view, final OnResultListener onResultListener){

            setSubscribe(observable, new BaseObserver<T>(view) {
                @Override
                public void onSuccess(T info) {
                    if(onResultListener!=null){
                        onResultListener.onSuccess(info);
                    }
                }
                @Override
                public void onError(Throwable e, String msg) {
                    Log.e("onError",e.getMessage());
                    errorDispose(e,msg,onResultListener);
                }
            });
        }

        /**
         *Post方式请求网络 view传null 不是mvp方式
         */
        public static void post(Observable observable,OnResultListener onResultListener){
             post(observable,null,onResultListener);
        }

        /**
         * 订阅事件
         */
        public static<T> void setSubscribe(Observable<T> observable, Observer<T> observer){
            observable
                    //开启新线程
                    .subscribeOn(Schedulers.newThread())
                    //ui操作放主线程
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
        }

        /**
         * 接口回调
         * @param <T>
         */
        public interface OnResultListener<T>{
            void onSuccess(T t);
            void onError(Throwable error, String msg);
        }

        /**
         * 错误处理
         * @param error
         * @param msg
         * @param resultListener
         */
        private static void errorDispose(Throwable error,String msg,OnResultListener resultListener) {
            if(error!=null && resultListener!=null){
                resultListener.onError(error,error.getMessage());
            }else if(resultListener!=null){
                resultListener.onError(new Exception("网络不给力"),"");
                Toast.makeText(MyApplication.getApplication(),"网络不给力",Toast.LENGTH_LONG).show();
                return;
            }

            String e  = error.getMessage();
            int code  =0;
            if(!TextUtils.isEmpty(e)){
                try {
                    e = e.substring(e.length()-3,e.length());
                    code = Integer.valueOf(e);
                }catch (Exception e1){
                    Toast.makeText(MyApplication.getApplication(),"网络不给力",Toast.LENGTH_LONG).show();
                }
            }
            Log.e("错误code",code+"");
            if(code >= 300 && code < 500){
                Toast.makeText(MyApplication.getApplication(),"您的请求迷路了,请稍后再试",Toast.LENGTH_LONG).show();
            }else if(code >= 500){
                Toast.makeText(MyApplication.getApplication(),"服务器异常,请稍后再试",Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(MyApplication.getApplication(),"网络不给力",Toast.LENGTH_LONG).show();
            }
        }
    }

6.MVP封装

    1. View层基类封装

    public interface IBaseView {
        /**
         * 数据请求失败 View层处理
         * @param msg
         */
        void onError(String msg);
        /**
         *请求成功关闭loading
         */
        void closeLoading();
        /**
         *添加Disposable
         * @param disposable
         */
        void addRxDisposable(Disposable disposable);
        /**
         *移除Disposable
         * @param disposable
         */
        void removeRxDisposable(Disposable disposable);
    }

    2. presenter层基类封装

    public abstract class BasePresenter <T extends IBaseView>{

        protected  T mView;
        protected Context mContext;
        public BasePresenter(T view,Context context){
            this.mView = view;
            this.mContext = context;
        }

        /**
         *请求网络 加载数据方法
         */
        public abstract void initData();

        /**
         *用于将View对象清空
         */
        public void onDestoryView() {
            if(mView !=null) {
                mView = null;
            }
        }
    }

    3. module层封装 接口通用属性都可以放在这里面

    public class BaseInfo {
    }

    4. 创建基于Activity的Module

    @Module
    public class MainModule {

        private IMainView mView;
        private CompositeDisposable disposables2Destroy;

        public MainModule(IMainView view){
            this.mView = view;
        }

        @ActivityScope
        @Provides
        public IMainView provideMainView(){
            return mView;
        }

        @ActivityScope
        @Provides
        public CompositeDisposable provideDisposable(){
            return  disposables2Destroy ==null ? new CompositeDisposable() : disposables2Destroy;
        }
    }

    5. 创建Activity的Component

    //生命周期管理
    @ActivityScope
    //很重要!这个Component是AppComponent的子Component,所以要使用Subcomponent这个注解
    //不使用@Component注解的Dependents属性是因为希望能统一管理子Component
    @Subcomponent(modules = MainModule.class)
    public interface MainComponent {
        /**
         * 方法参数中,只能传递被注入对象!要在哪个类中注入,写哪个类,注入到父类没用!
         * @param activity 
         */
        void inject(MainActivity activity);
    }

    6. 改造AppComponent(重要)

     MainComponent addSub(MainModule mainModule);

    7. 创建基于MainActivity的View接口

    public interface IMainView extends IBaseView{
        /**
         * 显示位置信息
         * @param info
         */
        void showLocationInfo(IPLocationInfo info);
    }

    8. 创建基于MainActivity的Presenter类

    public class MainPresenter extends BasePresenter<IMainView>{

        private final RetrofitService service;
        @Inject
        public MainPresenter(IMainView view, Context context,RetrofitService service) {
            super(view, context);
            this.service = service;
        }

        @Override
        public void initData() {
            getInfo();
        }

        public void getInfo(){
            HttpUtil.post(service.getIPInfo("61.135.169.121"), mView, new HttpUtil.OnResultListener<IPLocationInfo>() {
                @Override
                public void onSuccess(IPLocationInfo info) {
                    mView.showLocationInfo(info);
                }

                @Override
                public void onError(Throwable error, String msg) {
                    mView.onError(msg);
                }
            });
        }
    }

7.MainActivity实现

    public class MainActivity extends BaseActivity implements IMainView{

        //注入presenter 对象
        @Inject
        MainPresenter presenter;
        private TextView city;
        private TextView cityCode;
        private TextView ip;
        private TextView isp;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            initView();
            initData();
        }

        private void initView() {
            city = (TextView) findViewById(R.id.city);
            cityCode = (TextView) findViewById(R.id.cityCode);
            ip = (TextView) findViewById(R.id.ip);
            isp = (TextView) findViewById(R.id.isp);
        }

        private void initData() {
            MyApplication.getAppComponent()
                    .addSub(new MainModule(this))
                    .inject(this);
            presenter.initData();
        }

        @Override
        public void showLocationInfo(IPLocationInfo info) {
            city.setText(String.format("定位城市:%s", info.getData().getCity()));
            cityCode.setText(String.format("定位城市代码:%s", info.getData().getCity_id()));
            ip.setText(String.format("地位地区IP:%s", info.getData().getIp()));
            isp.setText(String.format("isp服务提供商:%s", info.getData().getIsp()));
        }

        @Override
        public void onError(String msg) {
            Toast.makeText(this,msg,Toast.LENGTH_LONG).show();
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            if(presenter!=null){
                presenter.onDestoryView();
            }
        }
    }

8.联系方式

QQ:1509815887
email:zlc921022@163.com

9.下载地址

点击去下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这里提供一个简单的 Android Dagger2 的案例 demo,使用 Dagger2 实现依赖注入,实现了一个简单的计算器功能。 首先,在 build.gradle 中添加依赖: ``` dependencies { implementation 'com.google.dagger:dagger:2.x' annotationProcessor 'com.google.dagger:dagger-compiler:2.x' } ``` 然后,定义依赖关系。在这个例子中,我们定义了两个依赖:Calculator 和 CalculatorModule。Calculator 是一个接口,CalculatorModule 是一个模块,其中包含了用于实例化 Calculator 对象的方法。 ``` public interface Calculator { int add(int a, int b); } @Module public class CalculatorModule { @Provides Calculator provideCalculator() { return new CalculatorImpl(); } } ``` 其中,CalculatorImpl 是 Calculator 接口的实现类,用于实现 add 方法。 ``` public class CalculatorImpl implements Calculator { @Override public int add(int a, int b) { return a + b; } } ``` 在 Activity 中,我们需要使用 Calculator 对象,可以通过 @Inject 注解实现依赖注入。 ``` public class MainActivity extends AppCompatActivity { @Inject Calculator calculator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DaggerCalculatorComponent.create().inject(this); int result = calculator.add(1, 2); Toast.makeText(this, "1 + 2 = " + result, Toast.LENGTH_SHORT).show(); } } ``` 其中,DaggerCalculatorComponent 是 Dagger2 自动生成的 Component 类,用于创建 Calculator 对象,并注入到 MainActivity 中。 最后,我们需要定义一个接口,用于将 CalculatorModule 和 MainActivity 连接起来。 ``` @Component(modules = {CalculatorModule.class}) public interface CalculatorComponent { void inject(MainActivity activity); } ``` 以上就是 Android Dagger2 的一个简单 demo。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值