RePlugin 插件共享宿主的Retrofit实例

最近在学习使用RePlugin,在考虑代码分层时,基本的网络请求要怎么共享,不管是宿主还是插件,对应的Retrofit实例和OKHTTP实例应该只有一个才对,如果每个app中一个单独的实例是可行,但是占用资源。

使用共享lib的方式来实现

网络层comm_net: 通过Retrofit2+Rxjava2+Dagger2来实现

HttpResult:数据返回的通用数据结构定义

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实例

@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模块中才会用,就不在基础的网络层去提供了,没价值而且会有依赖冲突

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,让依赖这个lib的项目可见
  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,让依赖这个lib的项目可见
}

当依赖了这些项目的时候,他们之前的依赖关系如下:

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);
    }
//省略部分无关代码
}
  • 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方法,并通过他在插件中创建定义的请求接口。

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;
  }
  
  //省略部分无关代码
  }
  • 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'
  }

编译运行后,ap中请求ok,但是插件中直接崩溃了,报错如下:

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转换Observable时失败了,找不匹配的转换器。

明明存在为啥找不到,怀疑是依赖class找不到

断点调试查看版本和路径

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


    image.png

returnType 的 io.reactivex.Observable 路径是不一样的。

所以需要移除插件里面的Observable,让它去吸附宿主里面的路径。

  • 于是调整 plugina的build,移除相关依赖

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')
}
//相当于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的依赖。

  • 同时要记得去app的MyApplication中去开启setUseHostClassIfNotFound(true),否则plugina中会找不到Retrofit和RxJava
image.png

或许你会纳闷为啥要把rxandroid抽成jar,并compileOnly,而不能直接implementation,然后单独移除Rxjava勒? 下面有图为证

image.png

编译会报错,提示不能把rxandroid作为仅编译时使用,记得上面的那个依赖图么,rxandroid依赖了Rxjava,现在釜底抽薪了,然后有要编译打包rxandroid,风险太高,系统自然不干。

看似简简单的几行代码,折腾了我一周的时间去各种验证和调整写法,心塞塞的。

在编译app是指定同时要编译的plugin插件,方便团队成员快速调试验证自己开发的插件,可以在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 前,先卸载对应版本,防止Replugin 插件的改动不更新
            tasks.getByPath(":${project.name}:assemble${buildType.name.capitalize()}").dependsOn "uninstall${buildType.name.capitalize()}"
            preAssemble.dependsOn subAssemble
        }
    }
}

moduleName指定了一个参与编译的插件数组,在准备好的时候,会将app的 preXX编译依赖到插件的assembleXX任务上,同时插件的assembleXX会在编译完后,将自己拷贝到app的assert目录下,并重命名。同时在app的 assembleXX编译前,先从手机上卸载掉老版本,防止Replugin的插件不更新。

后续完善

  1. 优化上面的编译脚本,多个插件可以方便的指定编译一个
  2. 将comm_net封装成单独的插件,供app和plugina使用。
  3. 插件在编译的时候,Replugin插件会自动uzip依赖的的各种lib,编译相当的慢,这里可以把插件中共用的无关的lib全部移除掉,反正宿主会提供,比如support包
  4. 插件作用独立app编译与作为插件时的dependence动态适应,不用手动去改
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,670评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,928评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,926评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,238评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,112评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,138评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,545评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,232评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,496评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,596评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,369评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,226评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,600评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,906评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,185评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,516评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,721评论 2 335

推荐阅读更多精彩内容