Android架构师之路-组件化入门

组件化与模块化

组件

组件指的是单一的功能组件,如视频组件(VideoSDK)、支付组件(PaySDK)、路由组件(Router)等,每个组件都能单独抽出来制作成SDK

模块

模块指的是独立的业务模块,如直播模块(LiveModule)、首页模块(HomeModule)、即时通信模块(IMModule)等。模块相对于组件来说粒度更大,模块可能包含多种不用的组件。

组件化开发的好处

(1)避免重复造轮子,可以节省开发和维护的成本。
(2)可以通过组件和模块为业务基准合理地安排人力,提高开发效率。
(3)不同的项目可以共用一个组件或模块,确保整体技术方案的统一性。
(4)为未来插件化共同用一套底层模型做准备

模块化开发的好处

(1)业务模块解耦,业务移植更加简单。
(2)多团队根据业务内容进行并行开发和测试。
(3)单个业务可以单独编译打包,加快编译速度。
(4)多个App共用模块,降低研发和维护成本。

多Module划分业务和基础功能,这个概念将作为组件化的基础。
组件化和模块化的本质思想是一样的,都是为了代码重用和业务解耦,区别在于模块化是业务导向,组件化是功能导向。组件化和模块化的划分将更好地为项目插件化开路。插件化的模块发布和正常发布有着非常大的差异,已经脱离了组件化和模块化的构建机制,插件化拥有更高效的业务解耦。

项目搭建

1.首先我们新建一个项目然后新建一个library(componentlib)和两个组件(logincomponent、minecomponent),如下图:


在这里插入图片描述

(1)app:应用层用于统筹全部组件,并输出生成App
(2)logincomponent和minecomponent作为组件来使用,包含一些简单的业务、比如登录、我的。
(3)componentlib:包含一些基础库和对基础库的封装,包含图片加载、网络加载,数据存储(正常是再抽离一层出来,作为Base层);还有作为通讯层,来进行各个组件的数据交互。

引用关系是app引用logincomponent和mincomponent,然后logincomponent和mincomponent引用componentlib;

2、项目中的配置
(1)在gradle.properties配置全局gradle环境


在这里插入图片描述

(2)app build.gradle的配置


在这里插入图片描述

在这里插入图片描述

logincomponent和minecomponent配置一样,下面是logincomponent build.gradle的配置
在这里插入图片描述

在这里插入图片描述

注意这里必须要配置两个AndroidManifest.xml,一个用于独立运行,一个用做组件


在这里插入图片描述

独立运行下的AndroidManifest如下:
在这里插入图片描述

作为组件的AndroidManifest.xml如下
在这里插入图片描述

minecomponent组件的配置一样,这里就不贴图了。

代码实现

配置完成后,我们就可以开始重头戏,撸代码。
组件化的时候我们首先要解决两个问题
1、回头看下项目结构图,由于App引用了logincomponent和minecomponent这个两个组件,而他们两个作为组件要怎么拿到App的Application这个项目唯一的全局上下文。
2、组件间如何通讯。

组件获取到上下文

对于问题1,我们可以在App层,通过反射将Application设置到两个组建中,这样组件就可以使用到App层的Application。
(1)首先在componentlib中定义接口IAppComponent:

public interface IAppComponent {
    void initializa(Application application);
}

(2)然后组件的Application继承该接口:

public class LoginApp extends Application implements IAppComponent {
    private static Application application;

    public static Application getApplicatoin(){
        return application;
    }

    //独立运行的时候,这里是入口
    @Override
    public void onCreate() {
        super.onCreate();
        initializa(this);
    }
    //这里获取到了全局的Application
    @Override
    public void initializa(Application application) {
        this.application = application;
    }
}

注意上面的onCreate()方法,作为组件的时候是不会被调用的,但是独立运行的时候onCreate就是入口了。

(3)App的Application通过反射进行组件的实例化

public class AppConfig {
    public static final String[] COMPONENTS = {
            "com.kangjj.logincomponent.LoginApp",
            "com.kangjj.manecomponent.MineApp"
    };
}
public class MainApp extends Application implements IAppComponent {
    private MainApp application;

    public MainApp getApplication() {
        return application;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initializa(this);
    }
    //组件实例化
    @Override
    public void initializa(Application application) {
        this.application = (MainApp) application;
        for (String component : AppConfig.COMPONENTS) {
            try {
                //通过反射获取到需要实例化的组件
                Class<?> clazz = Class.forName(component);  
                Object object = clazz.newInstance();
                //将实例化的对象强转为IAppComponent,然后进行组件的实例化
                if(object instanceof  IAppComponent){
                    ((IAppComponent)object).initializa(application);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

这样组件就获取到了全局的Application

组件通讯

在这里插入图片描述

(1)创建组件的通讯工厂管理类

public class ServiceFactory {
    private static final ServiceFactory instance = new ServiceFactory();
    public static ServiceFactory getInstance(){
        return instance;
    }
    private ServiceFactory(){}

    private ILoginService mLoginService;
    private IMineService mMineService;

    public ILoginService getLoginService() {
        //如果将登陆组件移除,App进行无登陆组件的业务
        if(mLoginService == null){
            mLoginService = new EmptyLoginService();
        }
        return mLoginService;
    }
    
    //设置logincomponent的通讯接口,在logincomponent的初始化的地方实现
    public void setLoginService(ILoginService loginService) {
        this.mLoginService = loginService;
    }

    public IMineService getMineService() {
        if(mMineService == null){
            mMineService = new EmptyMineService();
        }
        return mMineService;
    }

    public void setMineService(IMineService mineService) {
        this.mMineService = mineService;
    }
}

(2)定义ILoginService接口,该接口主要是用于两个类的实现:

public interface ILoginService {
    void launch(Context context, String targetClass);

    Fragment newUserInfoFragment(FragmentManager fragmentManager, int viewId, Bundle bundle);
}

logincomponent里的LoginService,这里进行启动组件的Actiivty,或者获取Fragment等操作。

public class LoginService implements ILoginService {
    @Override
    public void launch(Context context, String targetClass) {
        Intent intent = new Intent(context,LoginActivity.class);
        intent.putExtra(LoginActivity.EXTRA_TARGET_CLASS,targetClass);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    public Fragment newUserInfoFragment(FragmentManager fragmentManager, int viewId, Bundle bundle) {
        UserInfoFragment fragment = new UserInfoFragment();
        fragment.setArguments(bundle);
        fragmentManager.beginTransaction().add(viewId,fragment).commit();
        return fragment;
    }

}

componentlib的EmptyLoginService

public class EmptyLoginService implements ILoginService {
    @Override
    public void launch(Context context, String targetClass) {
    }

    @Override
    public Fragment newUserInfoFragment(FragmentManager fragmentManager, int viewId, Bundle bundle) {
        return null;
    }
}

(3)接下来是初始化LoginService

public class LoginApp extends Application implements IAppComponent {
    ···
    //省略一些代码
    
    @Override
    public void initializa(Application application) {
        this.application = application;
        ServiceFactory.getInstance().setLoginService(new LoginService());
    }
}

(4)调用,进行通讯
下面是LoginActivity和UserInfoFragment,前者在App进行启动调用,后者用来获取Fragment在App进行显示。

public class LoginActivity extends AppCompatActivity {
    public static final String EXTRA_TARGET_CLASS = "EXTRA_TARGET_CLASS";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
    }
}

public class UserInfoFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.userinfo_fragment,null);
    }
}

对应的布局文件是很简单的TextView,这里就不显示了。

App里MainActivity的使用:

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    //跳转到登录页面
    public void login(View view){
        ServiceFactory.getInstance().getLoginService().launch(this,"");
    }

    public void goMine(View view){
        ServiceFactory.getInstance().getMineService().launch(this,2 ,REQUEST_CODE);
    }
    //获取组件的Userinfo页面进行显示
    public void getFragment(View view){
        ServiceFactory.getInstance().getLoginService().newUserInfoFragment(getSupportFragmentManager(),R.id.container,new Bundle());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==REQUEST_CODE && resultCode==RESULT_OK){
            Toast.makeText(this,data.getStringExtra("fromMine"),Toast.LENGTH_LONG).show();
        }
    }
}

对应xml布局文件如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="login"
        android:onClick="login"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="go mine"
        android:onClick="goMine"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="get UserInfoFragment"
        android:onClick="getFragment"/>

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

(5)运行,运行前记得修改gradle.properties

#login组件独立运行的标志
loginRunAlone = false
#mine组件独立运行的标志
mineRunAlone = false

然后编译、运行。

总结

组件化并不复杂,本质上也是gradle配置的变化而已,组件化核心思想是面向接口变成,定义公公组件,所有组件都依赖公共组件。

代码入口

文章有何不妥之处,欢迎指正,与讨论,谢谢观看。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容