Android组件化之不同模块间 交互(activity互相跳转,数据互相传递,互相调用函数)

来源:互联网 发布:网络综艺节目受众人群 编辑:程序博客网 时间:2024/05/22 14:15
在组件化之前,业务发展不是很快的时候,这样是比较合适的,能一定程度地保证开发效率。
慢慢地代码量多了起来,开发人员也多了起来,业务发展也快了起来,或者由多个项目其实可以共用一些模块时,这时单一工程开发模式就会显露出一些弊端:
  • 耦合比较严重(因为没有明确的约束,「组件」间引用的现象会比较多)
  • 业务模块重用性较差
  • 业务方的开发效率不够高(只关心自己的组件,却要编译整个项目,与其他不相干的代码糅合在一起)
为了解决这些问题,就采取了「组件化」策略。它能带来这些好处:
  • 加快编译速度(不用编译主客那一大坨代码了)
  • 业务模块可以在不同项目中应用
  • 方便 QA 有针对性地测试
  • 提高业务开发效率


下面的这张图是项目依赖关系

由于组件化的内容网上资料较多 ,我来讲一些不一样的。模块化是用来降低耦合度,但是有时候难免会和其他模块有些交互(这也是自己在公司开发项目中遇到的),一个module可以调用被依赖module的类方法,而被依赖modle不能引入依赖module类。简而言之就是,依赖只能单向,不能是双向,就算你想Android Studio也不让。但有时候被依赖的module也需要一些依赖module的数据怎么办?我就讲一下不同Module之间怎么交互的。
一、Activity之间跳转,有几种方式,
1.隐式Intent,要跳转的Activity在Manifest.xml中声明,然后调用startActivity(new Intent("com.example.boost"))
<activity android:name="com.example.boost.BoostActivity">   <intent-filter>        <action android:name="com.gaolei" />    </intent-filter></activity>

2.
Manifest中Activity的data设计URI来接受跳转,然后调用startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("activity://applock")));  
<activity    android:name=".module.ui.activity.RecommendGuideActivity">    <intent-filter>        <action android:name="android.intent.action.VIEW" />        <category android:name="android.intent.category.DEFAULT" />        <category android:name="android.intent.category.BROWSABLE" />        <data android:scheme="activity" />        <data android:host="applock" />    </intent-filter></activity>
3.利用反射
Class clazz=Class.fromName("com.clean.spaceplus.MainActivity")startActivity(this,clazz);
4.可以看Demo中的代码,就是把不同Module的一些类 注册到一个都依赖的Module(如项目中的interface的ModuleDelegate),然后一个Module就可以获取到其他Module的一些类对象,从而调用那个类的方法进行一些操作,如跳转一些Activity。

下面是ModuleDelegate来注册不同模块的一些类,供其他模块调用
public class CleanDelegate {    private final Map<String, IDelegateFactory> factoryMap = new HashMap<>();    private static final CleanDelegate mInstance = new CleanDelegate();    private CleanDelegate() {    }    public static CleanDelegate getInstance() {        return mInstance;    }    public static void register(String key, IDelegateFactory factory) {        mInstance.factoryMap.put(key, factory);    }    public Bundle getData(String factoryCode, int code, Bundle args, Object... extras) throws DelegateException {        IDelegateFactory factory = factoryMap.get(factoryCode);        if (factory != null) {            IDataDelegate transfer = factory.getDataTransfer(code);            if (transfer != null) {                return transfer.getData(args, extras);            }        }        throw new DelegateException("unknow data transfer");    }}

二、如何获取其他Module的数据,也有几种方法
1、同样,可以看Demo中的代码,就是把不同Module的一些类 注册到一个都依赖的Module(如项目中的interface的ModuleDelegate),然后一个Module就可以获取到其他Module的一些类对象,从而调用那个类的方法进行一些操作,如获取一些数据。

下面这个类是Antivirus模块调用Boost模块的一些数据
public class AntivirusActivity extends Activity {    TextView text;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_submodule2);        text = findViewById(R.id.text);    }    public void getDataFromOtherModule(View view) {        Bundle bundle;        try {            bundle = new Bundle();            bundle.putString("gaolei", "beauty");            Bundle bundle1 = ModuleDelegate.getInstance().getData(BoostDelegateConsts.FACTORY, BoostDelegateConsts.DataCode.getTotalMemoryByte, bundle, AntivirusActivity.this);            String result = bundle1.getString("result");            text.setText(result);        } catch (Exception e) {            e.printStackTrace();        }    }}

2.如果调用其他模块的一些方法是执行一些耗时操作 ,那么我们就可以在其他模块的子线程中发送广播,这个模块来接受。广播不管是不是在子线程中都可以发送出去,关于广播是最基本的我就不多说
/** * @author gaolei * @Description:供Antivirus模块调用的类 * */public class GetSyncData implements IDataDelegate {    @Override    public Bundle getData(Bundle args, Object... extras) throws DelegateException {        if (extras.length > 0 && extras[0] != null) {            if (extras[0] instanceof Context) {                final Context context = (Context) extras[0];                new Thread() {                    public void run() {                        try {                            new Thread() {                                public void run() {                                    try {                                        //模拟耗时操作,在这个线程里可以做耗时操作,然后把数据通过广播传出去                                        Thread.sleep(3000);                                    } catch (InterruptedException e) {                                        e.printStackTrace();                                    }                                    Bundle bundle = new Bundle();                                    bundle.putString("result", "这是一条异步获取的数据从Boost模块");                                    Intent intent = new Intent("com.example.getdata");                                    intent.putExtras(bundle);                                    context.sendBroadcast(intent);                                }                            }.start();                        } catch (Throwable e) {                        }                    }                }.start();            }        }        return null;    }}

public class AntivirusActivity extends Activity {    TextView text;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_antivirus);        text=findViewById(R.id.text);        IntentFilter filter=new IntentFilter("com.example.getdata");        DataReceiver dataReceiver=new DataReceiver();        registerReceiver(dataReceiver,filter);    }    public void getDataFromOtherModule(View view) {        Bundle bundle;        try {            bundle = new Bundle();            bundle.putString("gaolei", "beauty");           Bundle bundle1= ModuleDelegate.getInstance().getData(BoostDelegateConsts.FACTORY, BoostDelegateConsts.DataCode.getTotalMemoryByte,bundle,AntivirusActivity.this);            String result=bundle1.getString("result");            text.setText(result);        } catch (Exception e) {            e.printStackTrace();        }    }      public void getSyncDataFromOtherModule(View view) {        Bundle bundle;        try {            bundle = new Bundle();            //这个地方是调用Boost模块,获取异步数据           Bundle bundle1= ModuleDelegate.getInstance().getData(BoostDelegateConsts.FACTORY, BoostDelegateConsts.DataCode.getSyncData,bundle,AntivirusActivity.this);        } catch (Exception e) {            e.printStackTrace();        }    }    public class DataReceiver extends BroadcastReceiver{        @Override        public void onReceive(Context context, Intent intent) {            Bundle bundle=intent.getExtras();            String data=bundle.getString("result");            text.setText(data);        }    }}

三、可以使用第三方框架EventBus,可参考:http://blog.csdn.net/lmj623565791/article/details/40794879



demo地址:https://github.com/gaoleiandroid1201/MultiModuleInteraction
阅读全文
0 0
原创粉丝点击