Android Learning Series (43)--using the event bus framework Eventbus and Otto

Source: Internet
Author: User
Tags eventbus

Event Bus Framework

A solution that provides a unified subscription for events, which is published to achieve communication between components.

Principle

Viewer mode.

Eventbus and Otto

First 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 Broadcastreceiver

At 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 article

Eventbus the method of fixing the OnEvent method as the Subscriber accepts the event, it should refer to the idea of "contract better than Configuration".

  1. 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;}}
  2. 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.    // ...}}
  3. 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 Chapter

Here 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.

  1. 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;}}  
  2. To avoid waste, Otto needs to implement the singleton itself, relative to Eventbus.getdefault ().

    publicclass AppConfig {privatestaticfinalnew Bus();publicstaticgetInstance() {    return BUS;}}
  3. 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.    // ...}}
  4. 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
    1. Using the idea of design patterns to solve problems, this is the true value of design patterns.
    2. 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 articles

Android 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 operation

more about Android Development articles

Android Learning Series (43)--using the event bus framework Eventbus and Otto

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.