在同一个应用内部传递消息时,可以使用第三方开源库EventBus。
当使用Android Studio开发时,只需要在项目中导入对org.greenrobot.eventbus的依赖后,即可使用。
本篇博客主要介绍 EventBus的使用方式及对应的注意事项。
现在假设后台服务需要向前台界面发送消息,那么后台服务可以这样使用EventBus:
.............
@Override
public boolean onStartJob(JobParameters params) {
..............
Resources res = getResources();
Intent i = PhotoGalleryActivity.newIntent(this);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
Notification notification = new NotificationCompat.Builder(this)
.setTicker(res.getString(R.string.new_pictures_title))
.setSmallIcon(android.R.drawable.ic_menu_report_image)
.setContentTitle(res.getString(R.string.new_pictures_title))
.setContentText(res.getString(R.string.new_pictures_text))
.setContentIntent(pi)
.setAutoCancel(true)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, notification);
//获取EventBus势力
EventBus eventBus = EventBus.getDefault();
//调用post接口,发送消息
//EventBusData是自定义的类
eventBus.post(new EventBusData(0));
jobFinished(params, false);
return true;
}
前台界面监听该消息的用法类似于:
public class VisibleFragment extends Fragment {
EventBus mEventBus;
@Override
public void onStart() {
super.onStart();
mEventBus = EventBus.getDefault();
//注册到EventBus上
mEventBus.register(this);
}
@Override
public void onStop() {
super.onStop();
//反注册
mEventBus.unregister(this);
}
//这个接口接收回调消息
@Subscribe
public void onEventMainThread(EventBusData data) {
................
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getContext());
notificationManager.cancel(data.getId());
..............
}
...........
}
使用这个方法,就可以让后台服务发送通知。
如果应用正在前台的话,可以取消通知的功能。
EventBus整个使用看起来还是比较简单的,但要注意一下几点:
1、EventBus的post接口,一定要传递一个对象;
同时,该对象的类型与onEventMainThread参数类型一致时,onEventMainThread接口才能够被回调。
即通过EventBus post多个不同的对象时,类型一致的onEventMainThread就会收到通知。
上面代码中,如果将EventBusData对象直接更改为int类型,同时更改onEventMainThread的接口类型为int,
onEventMainThread不会被回调。
2、使用EventBus时,onEventMainThread函数必须加上注解@Subscribe。
其实从代码的使用方式就可以看出来,使用EventBus时,并没有要求相关类继承第三方库中的对象。
因此,必须增加注解,EventBus才能知道回调哪个函数。
Subscribe注解必须通过下列代码导入:
import org.greenrobot.eventbus.Subscribe;
3、发送事件到EventBus后,可以实现以下接口:
onEvent
如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。
使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。
onEventMainThread
如果使用onEventMainThread作为订阅函数,那么不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执行。
这个在Android中是非常有用的,因为在Android中只能在UI线程中更新UI,所以在onEvnetMainThread方法中是不能执行耗时操作的。
onEventBackground
如果使用onEventBackgrond作为订阅函数,那么如果事件是在UI线程中发布出来的,那么onEventBackground就会在子线程中运行。
如果事件本来就是子线程中发布出来的,那么onEventBackground函数直接在该子线程中执行。
onEventAsync
使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync。