Event Bus FrameworkA solution that provides a unified subscription for events, which is published to achieve communication between components.
PrincipleViewer mode.
Eventbus and OttoFirst look at the official definition of Eventbus:
thatbetween Activities, Fragments, Threads, Services, etc. Less code, better quality.
Then see the official Otto definition:
iseventtoofwhileto communicate efficiently.
In summary, simplify communication within Android in-app components.
Compare BroadcastreceiverAt work, I used both Otto and Eventbus in two scenarios, one for the download manager to notify the current progress of each related activity, and one to set the app wallpaper.
From a single use view, Eventbus > Otto > Broadcastreceiver (Of course broadcastreceiver as the system's built-in components, there are some features not previously available).
Eventbus is the most concise, Otto most in line with guava Eventbus design ideas, broadcastreceiver the most difficult to use.
My personal first choice is eventbus.
Example: "Set Wallpaper"The basic use of the two big frameworks is very simple:
Eventbus's basic use official reference: Https://github.com/greenrobot/EventBus
Official reference for Otto's basic use: http://square.github.io/otto/
Eventbus Realization of the articleEventbus the method of fixing the OnEvent method as the Subscriber accepts the event, it should refer to the idea of "contract better than Configuration".
Define Eventmodel as a carrier for communicating data between components
publicclass WallpaperEvent {private Drawable wallpaper;publicWallpaperEvent(Drawable wallpaper) { this.wallpaper = wallpaper;}publicgetWallpaper() { return wallpaper;}publicvoidsetWallpaper(Drawable wallpaper) { this.wallpaper = wallpaper;}}
Define subscribers, and most importantly, the OnEvent method
Public class baseactivity extends Activity {@Overrideprotected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Eventbus.getdefault (). Register ( This); Initwallpaper ();}@Overrideprotected void OnDestroy() {Super. OnDestroy (); Eventbus.getdefault (). Unregister ( This);} Public void onEvent(Wallpaperevent wallpaperevent) {//Appconfig.swallpaperdrawable as a global static Varappconfig.swallpaperdrawable = Wallpaperevent.getwallpaper (); Initwallpaper ();}Private void Initwallpaper() {//Support custom Setting the wallpaper set the current activity background wallpaper According to appconfig.swallpaperdrawable, default values, etc. // ...}}
The post () method is used anywhere to publish messages (wallpapers, exactly wallpaperevent) to all baseactivity subclasses, for example:
Private void Downloadwallpapper(String src) {Imagel ' javaoader.getinstance (). LoadImage (SRC,NewSimpleimageloadinglistener () {@Override Public void Onloadingcomplete(String Imageuri, view view, Bitmap loadedimage) {Bitmapdrawable wallpaper =NewBitmapdrawable (Loadedimage);//presist the image URL for cacheSavewallpaper (Imageuri);//Notify all base activity to update wallpaperEventbus.getdefault (). Post (NewWallpaperevent (wallpaper)); Toast.maketext (wallpapeeventbusractivity. This, R.string.download_wallpaper_success, Toast.length_short). Show (); }@Override Public void onloadingfailed(String Imageuri, view view, Failreason Failreason) {Toast.maketext (wallpaperactivity). This, R.string.download_wallpaper_fail, Toast.length_short). Show (); } });}
The point is this sentence:
// 在任何地方调用下面的方法,即可动态全局实现壁纸设置功能EventBus.getDefault().post(new WallpaperEvent(wallpaper));
Otto Realization ChapterHere are a few points to note:
(1) Otto uses annotations to define the role of a subscription/publisher, @Subscribe as a subscriber, @Produce as a publisher, and the method name can be customized.
(2) Otto for performance, code intent is clear, @Subscribe, @Produce method must be defined on a direct action class, but not defined in the base class and inherited.
(3) Unlike Eventbus, publishers also need registers and unregister, and eventbus publishers are not required.
-
Defines Eventmodel as the carrier for communicating data between components
public class wallpaperevent {private drawable wallpaper; Public wallpaperevent (drawable wallpaper) {this . Wallpaper = wallpaper;} public drawable getwallpaper () {return Wallpaper;} public void setwallpaper (drawable Wallpaper) {this . Wallpaper = Wallpaper;}}
To avoid waste, Otto needs to implement the singleton itself, relative to Eventbus.getdefault ().
publicclass AppConfig {privatestaticfinalnew Bus();publicstaticgetInstance() { return BUS;}}
Define the Subscriber, in the method that accepts the event plus the modifier @subscribe in the method that accepts the event with the modifier at Subscribe
Public class baseactivity extends Activity {@Overrideprotected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Appconfig.getbusinstance (). Register ( This); Initwallpaper ();}@Overrideprotected void OnDestroy() {Super. OnDestroy (); Appconfig.getbusinstance (). Unregister ( This);} Public void onottoevent(Wallpaperevent wallpaperevent) {appconfig.swallpaperdrawable = Wallpaperevent.getwallpaper (); Initwallpaper ();}Private void Initwallpaper() {//Support custom Setting the wallpaper set the current activity background wallpaper According to appconfig.swallpaperdrawable, default values, etc. // ...}}
Define the publisher, and post the message anywhere
Public class wallpaperactivity extends baseactivity {PrivateDrawable wallpaperdrawable;//Here also to update their own wallpaper, so show the method of defining @subscribe@Subscribe Public void onwallpaperupdate(Wallpaperevent wallpaperevent) {Super. Onwallpaperupdate (wallpaperevent);}@Produce PublicWallpapereventPublishwallpaper() {return NewWallpaperevent (wallpaperdrawable);}Private void Downloadwallpapper(String src) {//... //Notify all @subscribe to match wallpaperevent parameter executionAppconfig.getbusinstance (). Post (Publishwallpaper ());//...}}
Summary
- Using the idea of design patterns to solve problems, this is the true value of design patterns.
- These two Android event bus frameworks provide a more flexible and powerful solution that is more perfect for decoupling, and in many cases it is better to learn from the development efficiency, execution performance and design ideas than broadcastreceiver.
Other great article articlesAndroid Learning Notes ($) Android Options Menu and submenu (submenu) Android Learning note (notification) features and usage of Android Learning notes ($) Android using listeners to listen to menu events Android Learning notes (+) Android Create a single-selection menu and a check menu for jquery tutorials ( -ajax operations based on request load Data jquery tutorial (-ajax) append HTML for operationmore about Android Development articles
Android Learning Series (43)--using the event bus framework Eventbus and Otto