Android模块化探索和实践(3):模块间彻底隔离

在上一篇文章中Android 模块化探索和实践(2):Dagger2实现模块化(组件化)实现了模块间的Dagger2注入,但是细心的读者应该会发现,那个模块化方案其实是不彻底,因为没有做到模块之间的彻底隔离。比如在主APP中,需要手动在build.gradle中引入module,这样就无法做到代码和资源隔离,这是不彻底的模块化方案。本篇文章主要解决这个问题

别人的方案

参考了很多大牛的模块化方案,找到了一个可行度高、风险可控、后期好维护的方案。这个就是目前“得到”采用的组件化方案,该方案详细说明可以参考得到:彻底组件化方案。该组件化方案的核心有两点:

  1. 通过Router实现各个组件的动态注册和动态卸载,同时,各个模块间通过接口实现数据交互,接口暴露出来,注册模块的同时接口也被注册到Router中;

注册模块方式如下:


Router.registerComponent("com.xud.modulea.BusinessAAppLike");

注册Service和使用Service方式如下:


Router.getInstance().addService(BusinessAService.class, new BusinessAServiceImpl());

Fragment fragment = Router.getInstance().getService(BusinessAService.class).getMainFragment();

  1. 实现了一个自定义的Gradle脚本,编译时根据模块下gradle.properties文件中配置的依赖组件名,往build.gradle文件中注入“api project(':component')”,实现了编译时组件依赖,从而达到了代码和资源的隔离。

// gradle.properties中的依赖配置示例

debugComponent=modulea,moduleb,modulekotlin

compileComponent=modulea,moduleb,modulekotlin

本文要解决的问题

本文就是在这个方案的基础上,对之前的方案做进一步的改进,主要解决的问题有三个:

  1. 明确模块之间的架构;

  2. 优化模块中Dagger2的注入;

  3. 支持Databinding

源码已经提交到Github,地址为 https://github.com/xudjx/DaggerModules

模块分层架构

能用图说明,就不废话了,见下图:

Android模块化分层架构.png

Dagger2注入的优化

各模块需要共享的实例注入写在BaseModule中。详细的原理我在文章中Android 模块化探索和实践(2):Dagger2实现模块化(组件化)有详细的介绍,这里只就优化点说明一下。

1、 简化业务模块的ModuleKit, 仅提供AppComponent的实例获取。以BusinessAModuleKit为例,其实现如下:

public class BusinessAModuleKit {

    private static BusinessAModuleKit instance;
    private AppComponent component;

    public static BusinessAModuleKit getInstance() {
        if (instance == null) {
            synchronized (BusinessAModuleKit.class) {
                if (instance == null) {
                    instance = new BusinessAModuleKit();
                }
            }
        }
        return instance;
    }

    public BusinessAModuleKit init(AppModuleComponentDelegate appModuleComponentDelegate) {
        this.component = appModuleComponentDelegate.initAppComponent();
        return this;
    }

    public AppComponent getComponent() {
        return component;
    }
}

2、 单独调试业务模块或者注册业务模块时,不要忘记初始化ModuleKit, 以BusinessAModuleKit的初始化为例

加载组件时的初始化过程

public class BusinessAAppLike implements IApplicationLike {

    private AppModuleComponentDelegate componentDelegate = new AppModuleComponentDelegate() {
        @Override
        public AppComponent initAppComponent() {
            BusinessAAppComponent appComponent = DaggerBusinessAAppComponent.builder()
                    .baseAppComponent(BaseModuleKit.getInstance().getComponent())
                    .build();
            return appComponent;
        }
    };

    @Override
    public void onCreate() {
        Router.getInstance().addService(BusinessAService.class, new BusinessAServiceImpl()); 

        // 初始化BusinessAModuleKit
        BusinessAModuleKit.getInstance().init(componentDelegate);
        ModuleAUIInterCeptor.isRegister = true;
    }

    @Override
    public void onStop() {
        Router.getInstance().removeService(BusinessAService.class);
        ModuleAUIInterCeptor.isRegister = false;
    }
}

单独调试时的初始化过程

public class BusinessAApplication extends BaseApplication {

    private AppModuleComponentDelegate componentDelegate = new AppModuleComponentDelegate() {
        @Override
        public AppComponent initAppComponent() {
            BusinessAAppComponent appComponent = DaggerBusinessAAppComponent.builder()
                    .baseAppComponent(BaseModuleKit.getInstance().getComponent())
                    .build();
            return appComponent;
        }
    };

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

    @Override
    public void initComponentDi() {
        BusinessAModuleKit.getInstance().init(componentDelegate);
    }

    @Override
    public void registerRouter() {
        RouterManager.initRouter(instance);
        Router.getInstance().addService(BusinessAService.class, new BusinessAServiceImpl());
    }
}

Databinding支持

在模块化方案中也是可以使用Databinding的,你只需要在各个模块的build.gradle添加


dataBinding {

 enabled = true

}

为了更方便各个业务模块之间共享Databinding基础组件,我将通用的Databinding Adapter注册在BaseModule,同时抽象出通用的BaseDataBindingActivity 和 BaseDataBindingFragment等。

以PicassoBindingAdapters为例:

public class PicassoBindingAdapters {

    @BindingAdapter(value = {"imageUrl"})
    public static void loadImage(ImageView view, String url) {
        PicassoHelperUtils.displayImage(url, view);
    }

    @BindingAdapter(value = {"imageUrl", "imageError"})
    public static void loadImage(ImageView view, String url, Drawable error) {
        PicassoHelperUtils.displayImage(url, view, error);
    }

    @BindingAdapter(value = {"imageUrl", "imageError", "imageWidth", "imageHeight", "imageCenterCrop"}, requireAll = false)
    public static void loadImage(ImageView view, String url, Drawable error, int width, int height, boolean centerCrop) {
        PicassoHelperUtils.displayImage(view, url, error, width, height, centerCrop);
    }
}

BaseDataBindingActivity的设计如下:

public abstract class BaseDataBindingActivity<T extends ViewDataBinding> extends BaseActivity {

    protected T mBinding;

    @Override
    protected final void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, getLayoutRes());
        onCreated(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        mBinding.unbind();
        super.onDestroy();
    }

    @LayoutRes
    protected abstract int getLayoutRes();

    protected void onCreated(Bundle savedInstanceState) {
    }
}

此外,需要提到的一点是,在Databinding页面中使用Dagger2有一点不一样的地方,即该页面注入的Component必须继承android.databinding.DataBindingComponent,否则会注入失败


@PerView

@Component(dependencies = BusinessAAppComponent.class, modules = BaseViewModule.class)

public interface DJDataBandingComponent extends android.databinding.DataBindingComponent {

 void inject(ModuleADatabandingActivity activity);

}

有了以上这些基础构件,在模块中使用Databinding就变得很简单了。首先,先创建module_a_fragment_databand.xml;

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="viewModel"
            type="com.xud.modulea.ui.ModuleADatabandingActivity.ViewModel" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical">

        <ImageView android:id="@+id/img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scaleType="centerCrop"
            app:imageUrl='@{"http://7xopuh.dl1.z0.glb.clouddn.com/pic06.jpg"}' />


        <TextView
            android:id="@+id/detail_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{viewModel.detail}"
            android:textSize="15dp"/>

    </LinearLayout>

</layout>

然后再创建ModuleADatabandingActivity,继承BaseDataBindingActivity。

public class ModuleADatabandingActivity extends BaseDataBindingActivity<ModuleAFragmentDatabandBinding> {

    private DJDataBandingComponent mDJDataBandingComponent;

    public DJDataBandingComponent dbComponent() {
        if(mDJDataBandingComponent == null) {
            mDJDataBandingComponent = DaggerDJDataBandingComponent.builder()
                    .businessAAppComponent((BusinessAAppComponent) BusinessAModuleKit.getInstance().getComponent())
                    .baseViewModule(new BaseViewModule(this))
                    .build();
        }
        return mDJDataBandingComponent;
    }

    @Inject
    BusinessAApi businessAApi;

    ViewModel viewModel;

    @Override
    protected void onCreated(Bundle savedInstanceState) {
        super.onCreated(savedInstanceState);
        dbComponent().inject(this);
        viewModel = new ViewModel();
        mBinding.setViewModel(viewModel);
        initData();
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.module_a_fragment_databand;
    }

    private void initData() {12·
        // todo
    }

    public class ViewModel {
        public ObservableField<String> detail = new ObservableField<>();
    }
}

帖的代码比较多,读者有兴趣的话,还是移步 https://github.com/xudjx/DaggerModules

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266

推荐阅读更多精彩内容