Android MVP入門到進階之- 系統(tǒng)框架集成(完結(jié))

前言

本系列共三篇:
Android MVP入門到進階之-簡單入門
Android MVP入門到進階之-結(jié)合Dagger2
Android MVP入門到進階之- 系統(tǒng)框架集成(完結(jié))

通過前兩篇文章,整理了 MVP的簡單框架的搭建MVP結(jié)合Dagger2 的使用的例子,如果你還不熟悉MVP的使用請先查看前兩篇文章:
Android MVP入門到進階之-簡單入門
Android MVP入門到進階之-結(jié)合Dagger2
這篇文章我們我們主要介紹,MVP 配合網(wǎng)絡(luò)框架Retrofit 的使用,因為我們APP開發(fā),網(wǎng)絡(luò)請求是很重要的一環(huán),當(dāng)然你也可以選擇自己喜歡的網(wǎng)絡(luò)框架進行封裝。這里我們只講解 Retrofit2 基于 Dagger2的封裝和在MVP框架中的使用。
如果你還不知道什么事Retrofit是什么,你可能還需要補充一下知識
你真的會用Retrofit2嗎?Retrofit2完全教程

正式開始

通過Android MVP入門到進階之-結(jié)合Dagger2的封裝之后,我們的主體框架已經(jīng)定型,所以我們只需要添加一個HttpMoudle就可以了,我們一步一步來添加

1. 在build.gradle中添加相關(guān)依賴

    /*gson 用于解析json數(shù)據(jù)*/
    implementation 'com.google.code.gson:gson:2.8.2'
    /*retrofit 網(wǎng)絡(luò)請求框架 + rxjava */
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    /*添加Gson適配器*/
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
    implementation 'com.squareup.retrofit2:converter-scalars:2.0.0'
    /*okhttp日志打印*/
    implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'
    /*rxjava*/
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
    implementation 'io.reactivex.rxjava2:rxjava:2.1.8'

2. 在AndroidManifest.xml 中添加網(wǎng)絡(luò)權(quán)限

    <!-- 用于訪問網(wǎng)絡(luò),網(wǎng)絡(luò)定位需要上網(wǎng) -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

添加BaseApiService接口 用于管理網(wǎng)絡(luò)請求接口和提供網(wǎng)絡(luò)請求的方法

/**
 * @desc BaseApiService   為Retrofit框架提供接口請求注解,也是我們的網(wǎng)絡(luò)接口管理類
 * @author Marlon
 * @date 2018/12/18
 */

public interface BaseApiService {
    String BASE_URL_ZHIHU = " http://news-at.zhihu.com/";

    @GET("/api/4/version/android/2.3.0")
    Observable<BaseResponse<Resond>> getVerisionRxjava();
}

書寫HttpMoudel

/**
 * @desc HttpModule
 * @author Marlon
 * @date 2017/12/18
 */
@Module
public class HttpModule {
    private static final String TAG = "HttpModule";
    private static final long TIMEOUT = 1000;

    @Singleton
    @Provides
        //構(gòu)建 Retrofit.Builder
    Retrofit.Builder provideRetrofitBuilder() {
        return new Retrofit.Builder();
    }

    @Singleton
    @Provides
        // 構(gòu)建 OkHttpClient.Builder
    OkHttpClient.Builder provideOkHttpBuilder() {
        return new OkHttpClient.Builder();
    }

    @Singleton
    @Provides
        //構(gòu)建 OkHttpClient 這里的攔截器 根據(jù)需求添加 需要才添加
    OkHttpClient provideClient(OkHttpClient.Builder builder) {
        CookieManger cookieJar =
                new CookieManger(App.getInstance());
        //儲存目錄
        File mFile = new File(App.getInstance().getCacheDir() + "http");
        // 10 MB 最大緩存數(shù)
        long maxSize = 10 * 1024 * 1024;
        Cache mCache = new Cache(mFile, maxSize);
        Map<String, String> headers = new HashMap<>();
        return builder
                //添加Cookie管理,不需要管理可以不加,token在Cookie中的時候需要添加
                .cookieJar(cookieJar)
                //添加統(tǒng)一的請求頭
                .addInterceptor(new BaseInterceptor(headers))
                //添加base改變攔截器
                .addInterceptor(new BaseUrlInterceptor())
                //添加緩存攔截器
                .addNetworkInterceptor(new CaheInterceptor(App.getInstance()))
                //打印請求信息(可以自定義打印的級別?。。?                .addNetworkInterceptor(new HttpLoggingInterceptor(message -> Log.e(TAG, message)).setLevel(HttpLoggingInterceptor.Level.BODY))
                //相關(guān)請求時間設(shè)置
                //鏈接時間
                .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                //讀取時間
                .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                //寫入時間
                .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                //添加緩存
                .cache(mCache)
                // 這里你可以根據(jù)自己的機型設(shè)置同時連接的個數(shù)和時間,我這里8個,和每個保持時間為15s
                .connectionPool(new ConnectionPool(8, 15, TimeUnit.SECONDS))
                .build();

    }

    @Singleton
    @Provides
        //構(gòu)建 Retrofit
    Retrofit provideMyRetrofit(Retrofit.Builder builder, OkHttpClient client) {
        return createRetrofit(builder, client, BaseApiService.BASE_URL_ZHIHU);
    }


    @Singleton
    @Provides
        //通過 反射機制 創(chuàng)建BaseApiService  這里BaseApiService 是封裝請求方法的接口類
    BaseApiService provideMyService(Retrofit retrofit) {
        return retrofit.create(BaseApiService.class);
    }

    /**
     * 通過Retrofit.Builder OkHttpClient url 構(gòu)建Retrofit
     * @param builder
     * @param client
     * @param url
     * @return
     */
    private Retrofit createRetrofit(Retrofit.Builder builder, OkHttpClient client, String url) {
        return builder.baseUrl(url)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

}

上面構(gòu)建OkHttpClient 的方法中涉及到很多的攔截器,詳細(xì)內(nèi)容請查看源碼demo。

在 AppComponent中添加一下內(nèi)容,將HttpModule 添加到注解中

/**
 * @desc AppComponent
 * @author Marlon
 * @date 2018/12/18
 */

@Singleton
@Component(modules = {AppModule.class, HttpModule.class})
public interface AppComponent {

    App getContext();  // 提供App的Context

    BaseApiService retrofitHelper();  //提供http的幫助類

}

在APP中加入HttpModule 關(guān)聯(lián)

/**
 * @desc App
 * @author Marlon
 * @date 2018/12/18
 */

public class App extends Application {
    private static App instance;
    public static AppComponent appComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static synchronized App getInstance() {
        return instance;
    }

    public static AppComponent getAppComponent() {
        if (appComponent == null) {
            appComponent = DaggerAppComponent.builder()
                    .appModule(new AppModule(instance))
                    .httpModule(new HttpModule())//這里添加
                    .build();
        }
        return appComponent;
    }

    public static void exitApp() {
        try {
            ActivityCollector.removeAllActivity();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }
}

書寫 RxPresenter 類使用

/**
 * @desc RxPresenter 基于Rx的Presenter封裝,控制訂閱的生命周期
 * @author Marlon
 * @date 2018/12/18
 */
public class RxPresenter<T extends BaseView> implements BasePresenter<T> {
    protected BaseApiService apiService;
    protected Context mContext;
    protected T mView;
    private CompositeDisposable mCompositeDisposable;

    public RxPresenter(App mContext, BaseApiService apiService) {
        this.apiService = apiService;
        this.mContext = mContext;
    }

    /**
     * 取消注冊 中斷請求
     */
    protected void unSubscribe() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.dispose();
            mCompositeDisposable.clear();
        }
    }

    //注冊
    protected void addSubscribe(Disposable subscription) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(subscription);
    }

    protected void addSubscribe(Observable<?> observable, BaseObserver observer) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(observable.compose(RxHelper.io_main(mContext)).subscribeWith(observer));
    }

    @Override
    public void attachView(T view) {
        this.mView = view;
    }

    @Override
    public void detachView() {
        this.mView = null;
        unSubscribe();
    }
}

MainPresenter 繼承 RxPresenter

/**
 * @desc MainPresenter
 * @author Marlon
 * @date 2018/12/18
 */
public class MainPresenter extends RxPresenter<MainContract.View> implements MainContract.Presenter {
    @Inject
    public MainPresenter(App app, BaseApiService service) {
        super(app, service);
    }


    @Override
    public void getVersion() {
        //使用方式一
        addSubscribe(apiService.getVerisionRxjava()
                .compose(RxHelper.io_main(mContext))
                .subscribeWith(new BaseObserver<Resond>() {
                    @Override
                    protected void onSuccess(Resond value) {
                        mView.showData(value.toString());
                    }


                    @Override
                    protected void onFailure(String message) {
                        mView.showData(message);
                    }
                }));
        //使用方式二
        addSubscribe(apiService.getVerisionRxjava(), new BaseObserver<Resond>() {

            @Override
            protected void onSuccess(Resond value) {

            }

            @Override
            protected void onFailure(String message) {

            }
        });
    }
}

總結(jié)

到這里 我們框架就完全封裝完成,可能你看到這里還很迷,確實我剛開始學(xué)的時候也很迷,所以你需要把
RxJava 2、Retrofit2、Dagger2 ,慢慢搞懂,然后照著demo寫一遍,理解一下,應(yīng)該還是不難,感覺用文字?jǐn)⑹鰧嵲谑遣缓脤?,如果有疑問,也可以留言哈,我明白的可以答疑?br> 本文源碼地址demo,如果對你有幫助,希望點一下小星星哈!
到此,我們MVP框架系列已經(jīng)完結(jié)了。。。后面可能回再寫一篇結(jié)合組件化的博客,以后再說吧。

本文章為原創(chuàng)博客,轉(zhuǎn)載請注明出處!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容