HermesEventBus
一个基于EventBus的、能在进程间发送和接收event的库,解决EventBus没有进程通信能力的问题。
使用场景:
在IPC或者插件开发中非常有用。
github地址:https://github.com/Xiaofei-it/HermesEventBus
设计思路:
每次一个event被发送都会经过以下四步:
1、使用Hermes库将event传递给主进程。
2、主进程使用EventBus在主进程内部发送event。
3、主进程使用Hermes库将event传递给所有的子进程。
4、每个子进程使用EventBus在子进程内部发送event。
使用方法:
在gradle文件中加入下面的依赖:
dependencies {
compile 'xiaofei.library:hermes-eventbus:0.3.0'
}
在Application的onCreate中加上以下语句进行初始化:
HermesEventBus.getDefault().init(this);
每次使用EventBus的时候,用HermesEventBus代替EventBus。
HermesEventBus.getDefault().register(this);
HermesEventBus.getDefault().post(new Event());
HermesEventBus也能够在一个进程间传递event,所以如果你已经使用了HermesEventBus,那么就不要再使用EventBus了。
如果进程不需要再发送和接受event,那么这个进程必须调用:
HermesEventBus.getDefault().destroy();
否则你会收到android.os.DeadObjectException
和其他一些异常。这些异常会打印一些异常信息但不会导致app崩溃。
选择一个app作为主app。你可以选择任意app作为主app,但最好选择那个存活时间最长的app。
在主app的AndroidManifest.xml中加入下面的service:
<service android:name="xiaofei.library.hermes.HermesService$HermesService0"/>
在app间收发的事件类必须有相同的包名、相同的类名和相同的方法。
务必记住在代码混淆的时候将这些类keep!!!
在主app的application类的onCreate方法中加入:
HermesEventBus.getDefault().init(this);
在其他app的Application类的onCreate方法中加入:
HermesEventBus.getDefault().connectApp(this, packageName);
“packageName”指的是主app的包名。
每次使用EventBus的时候,用HermesEventBus代替EventBus。
HermesEventBus.getDefault().register(this);
HermesEventBus.getDefault().post(new Event());
如果进程不需要再发送和接受event,那么这个进程必须调用:
HermesEventBus.getDefault().destroy();
否则你会收到android.os.DeadObjectException
和其他一些异常。这些异常会打印一些异常信息但不会导致app崩溃。
补充:
Hermes是一套新颖巧妙易用的Android进程间通信IPC框架。