RePlugin 插件共享宿主的Retrofit實(shí)例

最近在學(xué)習(xí)使用RePlugin,在考慮代碼分層時(shí)绅络,基本的網(wǎng)絡(luò)請求要怎么共享月培,不管是宿主還是插件,對應(yīng)的Retrofit實(shí)例和OKHTTP實(shí)例應(yīng)該只有一個(gè)才對恩急,如果每個(gè)app中一個(gè)單獨(dú)的實(shí)例是可行节视,但是占用資源蔓榄。

使用共享lib的方式來實(shí)現(xiàn)

網(wǎng)絡(luò)層comm_net: 通過Retrofit2+Rxjava2+Dagger2來實(shí)現(xiàn)

HttpResult:數(shù)據(jù)返回的通用數(shù)據(jù)結(jié)構(gòu)定義

package com.lehow.comm.net;

public class HttpResult<T> {

    public int code;
    public String msg;

    public T data;
    public Boolean error;
    public String token;
    public int userId;

    @Override
    public String toString() {
        return "BaseBean{" +
                "code=" + code +
                ", message='" + msg + '\'' +
                ", data=" + data +
                ", error=" + error +
                ", token=" + token +
                ", userId=" + userId +
                '}';
    }
}

NetModule:提供Retrofit實(shí)例

@Module
public class NetModule {
  private String API_HOST_URL;

  public NetModule(String API_HOST_URL) {
    this.API_HOST_URL = API_HOST_URL;
  }


  @Provides @Singleton public Retrofit provideRetrofit() {
    Retrofit.Builder builder = new Retrofit.Builder().baseUrl(API_HOST_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create());
    return builder
        .build();
  }
}

NetComponent:暴露DI接口

@Singleton
@Component(modules = NetModule.class)
public interface NetComponent {
    Retrofit getRetrofitInstance();
}

build文件凝颇,主要看dependencies的定義乳丰。由于rxandroid只有app模塊中才會(huì)用尺栖,就不在基礎(chǔ)的網(wǎng)絡(luò)層去提供了幢竹,沒價(jià)值而且會(huì)有依賴沖突

dependencies {
  implementation fileTree(include: ['*.jar'], dir: 'libs')
  implementation 'com.google.dagger:dagger:2.12'
  annotationProcessor 'com.google.dagger:dagger-compiler:2.12'
  api 'com.squareup.retrofit2:retrofit:2.3.0'//暴露api蝗柔,讓依賴這個(gè)lib的項(xiàng)目可見
  implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
  implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
//  api 'io.reactivex.rxjava2:rxandroid:2.0.1'
  api 'io.reactivex.rxjava2:rxjava:2.1.6'//指定RxJava的版本竟秫,并暴露api陪竿,讓依賴這個(gè)lib的項(xiàng)目可見
}

當(dāng)依賴了這些項(xiàng)目的時(shí)候牙丽,他們之前的依賴關(guān)系如下:

image.png

app(宿主)和plugina(插件)通過同樣的接口請求

public interface NetApiService {


  @GET("test/top-article") Observable<HttpResult<ArrayList<TopArticle>>> getTopArticle(
      @Query("publishTime") String publishTime, @Query("moveType") int moveType,
      @Query("limit") int limit);
}
public class TopArticle {

  public int id;
  public String title;
  public String publishTime;
  public String backGroundPic;
  public int readNum;
  public String shortContent;
  public String url;
  public String logo;
  public int concernNum;
  public String realName;
  public boolean isCollect;
  }

兩者的不同在各自的application和build中:

app的定義:

  • MyApplication简卧,注意其中的createNetService方法
public class MyApplication extends RePluginApplication {
    private static final String TAG =MyApplication.class.getSimpleName() ;

    public static MyApplication instance;

    private Retrofit retrofitInstance;
    @Override public void onCreate() {
        super.onCreate();
        instance = this;
        retrofitInstance = DaggerNetComponent.builder()
            .netModule(new NetModule("http://192.168.10.224:7080/"))
            .build()
            .getRetrofitInstance();
    }
    public <T> T createNetService(final Class<T> service) {
        Log.i(TAG, "createNetService: retrofitInstance="+retrofitInstance);
        return retrofitInstance.create(service);
    }
//省略部分無關(guān)代碼
}
  • build的dependencies
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile('com.android.support:appcompat-v7:26.+', {
        exclude group: 'com.android.support', module: 'v4'
    })
    compile 'com.qihoo360.replugin:replugin-host-lib:2.2.1'
    testCompile 'junit:junit:4.12'
    implementation project(':comm_net')
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
}

plugina的定義:

  • MyApplication

這里面通過反射拿到app的MyApplication對象的createNetService方法,并通過他在插件中創(chuàng)建定義的請求接口烤芦。

public class MyApplication extends Application {
  private static final String TAG ="MyApplication" ;
  public static MyApplication instance;


  private Method createNetService;

  @Override protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
  }

  @Override public void onCreate() {
    super.onCreate();
    instance = this;
    //獲取宿主的context举娩,指向app的MyApplication對象
    Context hostContext = RePlugin.getHostContext();
    Class<? extends Context> aClass = hostContext.getClass();
    try {
      //反射拿到app中MyApplication對象的createNetService方法
      createNetService = aClass.getDeclaredMethod("createNetService", Class.class);
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    }

  }

  //返回Retrofit的接口對象
  public <T> T createNetService(final Class<T> service) {
    if (createNetService != null) {
      try {
        return (T) createNetService.invoke(RePlugin.getHostContext(), service);
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }
    return null;
  }
  
  //省略部分無關(guān)代碼
  }
  • build的dependencies
dependencies {
  implementation 'com.qihoo360.replugin:replugin-plugin-lib:2.2.1'
  testImplementation 'junit:junit:4.12'
  implementation 'com.android.support:appcompat-v7:26.1.0'
  implementation project(':comm_net')
  implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
  }

編譯運(yùn)行后,ap中請求ok,但是插件中直接崩潰了铜涉,報(bào)錯(cuò)如下:

Caused by: java.lang.IllegalArgumentException: Unable to create call adapter for io.reactivex.Observable<com.lehow.comm.net.HttpResult<java.util.ArrayList<com.lehow.plugina.net.TopArticle>>>
   for method NetApiService.getTopArticle
   at retrofit2.ServiceMethod$Builder.methodError(ServiceMethod.java:752)
   at retrofit2.ServiceMethod$Builder.createCallAdapter(ServiceMethod.java:237)
   at retrofit2.ServiceMethod$Builder.build(ServiceMethod.java:162)
   at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:170)
   at retrofit2.Retrofit$1.invoke(Retrofit.java:147)
   at java.lang.reflect.Proxy.invoke(Proxy.java:393)
   at $Proxy0.getTopArticle(Unknown Source)
   at com.lehow.plugina.MainActivity.btnGetTop(MainActivity.java:68)
    ... 11 more
Caused by: java.lang.IllegalArgumentException: Could not locate call adapter for io.reactivex.Observable<com.lehow.comm.net.HttpResult<java.util.ArrayList<com.lehow.plugina.net.TopArticle>>>.
 Tried:
  * retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
  * retrofit2.ExecutorCallAdapterFactory
   at retrofit2.Retrofit.nextCallAdapter(Retrofit.java:241)
   at retrofit2.Retrofit.callAdapter(Retrofit.java:205)
   at retrofit2.ServiceMethod$Builder.createCallAdapter(ServiceMethod.java:235)
    ... 17 more

Retrofit在使用RxJava2CallAdapterFactory轉(zhuǎn)換Observable時(shí)失敗了智玻,找不匹配的轉(zhuǎn)換器。

明明存在為啥找不到芙代,懷疑是依賴class找不到

斷點(diǎn)調(diào)試查看版本和路徑

  • APP中的信息
image.png
  • plugina中的信息


    image.png

returnType 的 io.reactivex.Observable 路徑是不一樣的吊奢。

所以需要移除插件里面的Observable,讓它去吸附宿主里面的路徑纹烹。

  • 于是調(diào)整 plugina的build,移除相關(guān)依賴

dependencies {
  implementation 'com.qihoo360.replugin:replugin-plugin-lib:2.2.1'
  //  implementation fileTree(include: ['*.jar'], dir: 'libs')
  testImplementation 'junit:junit:4.12'
  implementation 'com.android.support:appcompat-v7:26.1.0'
  implementation project(':comm_net')
  //  implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
  compileOnly files('libs/rxandroid-2.0.1.jar')
  //  implementation files('libs/retrofit-2.3.0.jar')
}
//相當(dāng)于compileOnly
android.applicationVariants.all { variant ->
    //移除從comm_net中來的retrofit2
  variant.getRuntimeConfiguration().exclude group: 'com.squareup.retrofit2'
  //移除從comm_net中的rxjava2
  variant.getRuntimeConfiguration().exclude group: 'io.reactivex.rxjava2'

}

注意compileOnly只能用在jar上页滚,所以要把rxandroid.aar中的jar包提取出來,才能用铺呵。而且移除了Rxjava和Retrofit的依賴裹驰。

  • 同時(shí)要記得去app的MyApplication中去開啟setUseHostClassIfNotFound(true),否則plugina中會(huì)找不到Retrofit和RxJava
image.png

或許你會(huì)納悶為啥要把rxandroid抽成jar片挂,并compileOnly邦马,而不能直接implementation,然后單獨(dú)移除Rxjava勒宴卖? 下面有圖為證

image.png

編譯會(huì)報(bào)錯(cuò)滋将,提示不能把rxandroid作為僅編譯時(shí)使用,記得上面的那個(gè)依賴圖么症昏,rxandroid依賴了Rxjava随闽,現(xiàn)在釜底抽薪了,然后有要編譯打包rxandroid肝谭,風(fēng)險(xiǎn)太高掘宪,系統(tǒng)自然不干。

看似簡簡單的幾行代碼攘烛,折騰了我一周的時(shí)間去各種驗(yàn)證和調(diào)整寫法魏滚,心塞塞的。

在編譯app是指定同時(shí)要編譯的plugin插件坟漱,方便團(tuán)隊(duì)成員快速調(diào)試驗(yàn)證自己開發(fā)的插件鼠次,可以在app的build中添加如下的腳本


def moduleName=[':plugina']

afterEvaluate {
    android.buildTypes.all{ buildType ->
        println 'buildType='+buildType
        println 'buildType capitalize='+buildType.name.capitalize()
        moduleName.each {curMName->
                println 'TTT='+"${curMName}:assemble${buildType.name.capitalize()}"
            curMName=curMName.replace(':','')
            def subAssemble=rootProject.project(curMName).tasks.
                getByPath(":$curMName:assemble${buildType.name.capitalize()}")
            subAssemble.doLast {
                println '==doLast=='
                copy{
                    from "../$curMName/build/outputs/apk/$buildType.name/$curMName-${buildType.name}.apk"
                    into "/src/main/assets/plugins/"
                    rename("$curMName-${buildType.name}.apk","${curMName}.jar")
                }
            }
            def preAssemble=tasks.getByPath(":${project.name}:pre${buildType.name.capitalize()}Build")
            //assemble 前,先卸載對應(yīng)版本芋齿,防止Replugin 插件的改動(dòng)不更新
            tasks.getByPath(":${project.name}:assemble${buildType.name.capitalize()}").dependsOn "uninstall${buildType.name.capitalize()}"
            preAssemble.dependsOn subAssemble
        }
    }
}

moduleName指定了一個(gè)參與編譯的插件數(shù)組腥寇,在準(zhǔn)備好的時(shí)候,會(huì)將app的 preXX編譯依賴到插件的assembleXX任務(wù)上觅捆,同時(shí)插件的assembleXX會(huì)在編譯完后赦役,將自己拷貝到app的assert目錄下,并重命名栅炒。同時(shí)在app的 assembleXX編譯前掂摔,先從手機(jī)上卸載掉老版本术羔,防止Replugin的插件不更新。

后續(xù)完善

  1. 優(yōu)化上面的編譯腳本乙漓,多個(gè)插件可以方便的指定編譯一個(gè)
  2. 將comm_net封裝成單獨(dú)的插件级历,供app和plugina使用。
  3. 插件在編譯的時(shí)候簇秒,Replugin插件會(huì)自動(dòng)uzip依賴的的各種lib,編譯相當(dāng)?shù)穆惚蓿@里可以把插件中共用的無關(guān)的lib全部移除掉趋观,反正宿主會(huì)提供,比如support包
  4. 插件作用獨(dú)立app編譯與作為插件時(shí)的dependence動(dòng)態(tài)適應(yīng)锋边,不用手動(dòng)去改
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末皱坛,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子剩辟,更是在濱河造成了極大的恐慌,老刑警劉巖往扔,帶你破解...
    沈念sama閱讀 221,635評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件贩猎,死亡現(xiàn)場離奇詭異吭服,居然都是意外死亡艇棕,警方通過查閱死者的電腦和手機(jī)瑟慈,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人雁乡,你說我怎么就攤上這事悠抹×呵穑” “怎么了掏觉?”我有些...
    開封第一講書人閱讀 168,083評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長值漫。 經(jīng)常有香客問我澳腹,道長,這世上最難降的妖魔是什么杨何? 我笑而不...
    開封第一講書人閱讀 59,640評論 1 296
  • 正文 為了忘掉前任酱塔,我火速辦了婚禮,結(jié)果婚禮上危虱,老公的妹妹穿的比我還像新娘羊娃。我一直安慰自己,他們只是感情好埃跷,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,640評論 6 397
  • 文/花漫 我一把揭開白布蕊玷。 她就那樣靜靜地躺著邮利,像睡著了一般。 火紅的嫁衣襯著肌膚如雪垃帅。 梳的紋絲不亂的頭發(fā)上延届,一...
    開封第一講書人閱讀 52,262評論 1 308
  • 那天,我揣著相機(jī)與錄音贸诚,去河邊找鬼方庭。 笑死,一個(gè)胖子當(dāng)著我的面吹牛酱固,可吹牛的內(nèi)容都是我干的械念。 我是一名探鬼主播,決...
    沈念sama閱讀 40,833評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼媒怯,長吁一口氣:“原來是場噩夢啊……” “哼订讼!你這毒婦竟也來了髓窜?” 一聲冷哼從身側(cè)響起扇苞,我...
    開封第一講書人閱讀 39,736評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎寄纵,沒想到半個(gè)月后鳖敷,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,280評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡程拭,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,369評論 3 340
  • 正文 我和宋清朗相戀三年定踱,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片恃鞋。...
    茶點(diǎn)故事閱讀 40,503評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡崖媚,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出恤浪,到底是詐尸還是另有隱情畅哑,我是刑警寧澤,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布水由,位于F島的核電站荠呐,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏砂客。R本人自食惡果不足惜泥张,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,870評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望鞠值。 院中可真熱鬧媚创,春花似錦、人聲如沸彤恶。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,340評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至歇竟,卻和暖如春挥唠,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背焕议。 一陣腳步聲響...
    開封第一講書人閱讀 33,460評論 1 272
  • 我被黑心中介騙來泰國打工宝磨, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人盅安。 一個(gè)月前我還...
    沈念sama閱讀 48,909評論 3 376
  • 正文 我出身青樓唤锉,卻偏偏與公主長得像,于是被迫代替她去往敵國和親别瞭。 傳聞我的和親對象是個(gè)殘疾皇子窿祥,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,512評論 2 359

推薦閱讀更多精彩內(nèi)容