RePlugin 插件共享宿主的Retrofit实例

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

使用共享lib的方式来实现

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

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

package com.lehow.comm.net;

public class HttpResult {

    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的项目可见
}

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

RePlugin 插件共享宿主的Retrofit实例_第1张图片
image.png

app(宿主)和plugina(插件)通过同样的接口请求

public interface NetApiService {


  @GET("test/top-article") Observable>> 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 createNetService(final Class 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 aClass = hostContext.getClass();
    try {
      //反射拿到app中MyApplication对象的createNetService方法
      createNetService = aClass.getDeclaredMethod("createNetService", Class.class);
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    }

  }

  //返回Retrofit的接口对象
  public  T createNetService(final Class 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>>
   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>>.
 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中的信息
RePlugin 插件共享宿主的Retrofit实例_第2张图片
image.png
  • plugina中的信息


    RePlugin 插件共享宿主的Retrofit实例_第3张图片
    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
RePlugin 插件共享宿主的Retrofit实例_第4张图片
image.png

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

RePlugin 插件共享宿主的Retrofit实例_第5张图片
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动态适应,不用手动去改

你可能感兴趣的:(RePlugin 插件共享宿主的Retrofit实例)