Android--Eventbus use

Source: Internet
Author: User

Eventbus

The Eventbus is an android-optimized publish/subscribe messaging bus that simplifies communication between components within an application and between components and background threads. such as requesting the network, and so on when the network returns through the handler or broadcast notification UI, two fragment between the need for listener communication, these requirements can be achieved through Eventbus .

As a message bus, there are three main elements:

    • Event: Events
      • Can be any type of object.
    • Subscriber: Event subscribers, receiving specific events
      • In Eventbus, you use conventions to specify event subscribers for ease of use. That is, all event subscriptions are functions that begin with onevent, specifically, the name of the function is Onevent,oneventmainthread,oneventbackgroundthread,oneventasync four, This is related to Threadmode.
    • Publisher: Event Publisher to notify Subscriber that an event has occurred
      • You can send an event anywhere on any thread, call the Eventbus ' post (object) method directly, and instantiate the Eventbus object yourself, but generally use the default singleton as well: ' Eventbus.getdefault () ', The function that subscribes to the corresponding type of event is automatically invoked based on the type of the post function parameter.
Threadmode

Each event subscription function is associated with a ' threadmode ', and Threadmode specifies the function that will be called. The following four Threadmode are available:

    • Postthread: The handling of events in the same process as the sending of events, so the event processing time should not be too long, otherwise affect the sending thread of the event, and this thread may be the UI thread. The corresponding function name is onevent.
    • Mainthread: The handling of the event is performed in the UI thread. Event processing time can not be too long, this needless to say, long will be ANR, the corresponding function name is Oneventmainthread.
    • Backgroundthread: The handling of the event is executed in a background thread, the corresponding function name is Oneventbackgroundthread, although the name is Backgroundthread, event processing is in the background thread, However, the event processing time should not be too long, because if the thread that sends the event is a background thread, the event is executed directly, if the current thread is the UI thread, the event is added to a queue, the events are processed sequentially by a single thread, and if an event is too long, it blocks the dispatch or processing of subsequent events.
    • Async: Event handling executes in a separate thread, primarily for time-consuming operations in a background thread, each of which turns on one thread (the cable pool), but it is best to limit the number of threads.

Depending on the function name of the event subscription, a different threadmode is used, and the subscriber simply names the function Oneventmainthread if the data is downloaded in the background line loads to be displayed in the UI thread.

Use process

Define the event type:

 Public class MyEvent {}

Define Event handling methods:

 Public void Oneventmainthread

Registered Subscribers:

Eventbus.getdefault (). Register (this)

Send event:

Eventbus.getdefault (). Post (new MyEvent ())
Sample
 Public classMainactivityextendsactionbaractivity {Privateconditionvariable mconditionvariable; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Mconditionvariable=Newconditionvariable (); Eventbus.getdefault (). Register ( This);        Initui (); StartActivity (NewIntent ( This, Twoactivity.class)); NewThread (NewSleepthread ()). Start (); } @Overrideprotected voidOnDestroy () {Super. OnDestroy (); Eventbus.getdefault (). Unregister ( This);    } TextView Mtxtone; Private voidInitui () {Mtxtone=(TextView) Findviewbyid (R.id.txt_one); }     Public voidOneventmainthread (Eventone eventone) {log.i ("Mainactivity", "mainactivity,,, Oneventmainthread");    Mtxtone.settext (Eventone.getstring ()); }//Public void Oneventasync (Eventone eventone) {//log.i ("mainactivity", "ONEVENTASYC--->" + thread.currentthread (). GetName ());//    }////Public void Oneventbackgroundthread (Eventone eventone) {//log.i ("mainactivity", "Oneventbackgroundthread--->" + thread.currentthread (). GetName ());//    }//Public void Oneventpostthread (Eventone eventone) {//log.i ("mainactivity", "Oneventpostthread--->" + thread.currentthread (). GetName ());//    }    classSleepthreadImplementsRunnable {@Override Public voidrun () {LOG.I ("Activity", "mainactivity,,, sleepthread--->begin"); Mconditionvariable.block (2000); LOG.I ("Activity", "mainactivity,,, sleepthread--->end"); Eventbus.getdefault (). Post (NewEventone ("11111")); }    }}

Eventone Code:

 Public class Eventone {    string string;      Public Eventone (String string) {        this. String = string;    }       Public string getString () {        return  String;    }}

Android--Eventbus use

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.