Otto is a Eventbus type of event transport bus that provides "store-and-forward" functionality, making it easier to communicate the various components of your app, and to make your programs more layered.
Working with scenes
Otto is based on the observer design pattern. It has publishers, subscribers to these two main objects. The best practice of Otto is to sacrifice the small performance by reflection, and greatly improve the coupling degree of the program, which is more advantageous to the development and maintenance of the MVP division. When the business layer developer processes the resources (such as DB, rest, etc.) and publishes the message, the presentation layer developer (such as activity/fragment) can process the message without having to worry about how the data came in (when reading the newspaper, you need to know how the editors are typesetting and printing it?). ), such as:
Communication between fragment,service or activity components. Like what
The Navigationdrawer of navigation menu and the communication of activity
The activity communicates with the activity (the night mode is checked on the setup interface, and the color is finished when you return to the main interface; or you click on the detailed interface, and return to the main interface to find that you have added a "praise")
MVP (model View presidenter) architecture, model and presidenter back-fall communication. Includes but is not limited to rest, DB, SP, Broadcastreceiver, Contentobserver.
One, Android studio configuration otto (direct download jar package import in eclipse)
As with the other frameworks described earlier, it simply needs to configure the following sections in Build.gradle
dependencies {
Compile filetree (dir: ' Libs ', include: [' *.jar '])
compile ' com.android.support:appcompat-v7 : 19.+ '
/
/otto need to depend on the package
}
Second, start to use
1. Subscribers '
when you want to subscribe, first open the registration (such as the life cycle of the Start/recovery section)
When you stop focusing on something, you need to unregister (such as the Stop/pause section of the lifecycle)
When you are interested in something, join @subscribe for attention.
@Subscribe public void GetMessage (@NonNull someevent s) {
//todo: Use this event in back-fall
2. Publishers '
when you want to post a message, use post to notice that the Publisher also needs to register in advance.
Example description
This paper takes SMS service acceptance as an example to introduce the use of Otto.
1. Constructing a single case pattern
Bus is a single example, so we want to create a single case pattern, and the simplest single example of course is built in application, remember to register in manifest Oh.
/**
* Created by Leon on 15/5/27.
* Main thread event bus, easy to return in asynchronous task
/Public
class Mainthreadbus extends bus {
private final Handler Handler = new Handler (L Ooper.getmainlooper ());
@Override public void Post (final Object event) {
if (looper.mylooper () = Looper.getmainlooper ()) {
//call directly via reflection C9/>super.post (event);
} else {
//through Handler the asynchronous task is sent to the UI thread and then the reflection calls
Handler.post (new Runnable () {
@Override public
void Run ( ) {
MainThreadBus.super.post (event);}}
);
}}
Then there's the application rewrite.
public class Globalcontext extends application {
//event bus singleton public
static final Mainthreadbus bus = new Mainthreadbus ();
public static Globalcontext instance;
@Override public void OnCreate () {
super.oncreate ();
instance = this;
}
public static Mainthreadbus Getbusinstance () {return bus
;
}
public static Globalcontext Getcontextinstance () {return
instance;
}
}
2. Sender (Publisher)
now we want to register a message receiving machine, in order to and domestic cancer software to preempt the first SMS listening, we use the service dynamic register receiver to preempt the first priority.
The establishment of a permanent background service, dynamic registration receiver to preempt the first priority. Also remember to put the service in manifest registration OH.
public class SMSService extends Service {private smsreceiver mreceiver = null; Public SMSService () {} @Override public ibinder onbind (Intent Intent) {//Todo:return the communication channel to
The service.
throw new Unsupportedoperationexception ("not yet implemented");
@Override public void OnCreate () {super.oncreate ();
LOG.D (TAG, "onCreate"); Intentfilter iFilter = null; Intent to filter Object mreceiver = new Smsreceiver ();
Broadcast Receive class initialization IFilter = new Intentfilter ("Android.provider.Telephony.SMS_RECEIVED"); Ifilter.setpriority (Integer.max_value); Set Priority Globalcontext.getbusinstance (). Register (mreceiver);//Registered Bus Registerreceiver (Mreceiver, IFilter);
Registration broadcast} @Override public void OnDestroy () {Super.ondestroy (); if (mreceiver!= null) {globalcontext.getbusinstance (). Unregister (mreceiver);//Unregister bus unregisterreceiver (mReceiver
); }
}
}
Then there is the real publisher Smsreceiver, most of the code is the same as the Internet, and notice how I posted the message.
public class Smsreceiver extends Broadcastreceiver {public
smsreceiver () {
}
@Override public void OnReceive (context context, Intent Intent) {
Bundle Bundle = Intent.getextras ();
Get the Protocol data unit of the link layer
object[] messages = (object[]) bundle.get ("PDUs");
smsmessage[] SMS = new Smsmessage[messages.length];
Create messages for each incoming PDU for
(int n = 0; n < messages.length; n++) {
Sms[n] = smsmessage.creat EFROMPDU ((byte[]) messages[n]);
}
for (Smsmessage msg:sms) {
//todo: This should add your own filter conditions, such as cell phone number, SMS content
//intercept SMS as much as possible, this command is not used
on Miui,flyme Abortbroadcast ();
Globalcontext.getbusinstance (). Post (msg);}}}
As can be seen from the code, in the service, we control the life cycle of the bus in Smsreceiver, then in the Smsreceiver, post the message out
Globalcontext.getbusinstance (). Post (msg);
3. Recipient (subscriber)
the receiver can be an activity, it can be a fragment, or it can be a service.
We take fragment as an example to operate.
public class Smscontrolfragment extends Fragment
= Globalcontext.getbusinstance ();
@Override public void Onattach [activity activity] {
Super.onattach (activity);
Bus.register (this);
}
@Override public void Ondetach () {
super.ondetach ();
Bus.unregister (this);
}
@Subscribe public void GetMessage (Smsmessage s) {
mtvnumber.settext (s.getoriginatingaddress ());
Mtvmessage.settext (S.getmessagebody ());
}
Subscriber is fragment, Publisher is Smsreceiver, message content is smsmessage.
By doing this, a messaging bus using Otto is complete.
4. Integrated Demo
the demo below, just to let everyone know that "event" was generated, post out, all the classes subscribed to the event will receive the event, the order of acceptance, not controlled by us!
public class MyActivity extends actionbaractivity {@Override protected void onCreate (Bundle savedinstancestate) {s
Uper.oncreate (savedinstancestate);
Setcontentview (r.layout.activity_my); Findviewbyid (R.id.button_change). Setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View
View) {busprovider.getbusinstance (). Post (new Datachangedevent ("This is changed String");//Publish Event}});
} @Override protected void Onresume () {super.onresume ();
Busprovider.getbusinstance () register (this);//registration} @Override protected void OnPause () {super.onpause (); Busprovider.getbusinstance (). Unregister (this);/logoff} @Subscribe//subscription event datachangedevent public void Saygoodonevent (Da
Tachangedevent event) {LOG.E ("event", "good");
@Subscribe//Subscribe event public void Saybadonevent (Datachangedevent event) {LOG.E ("event", "bad"); @Produce//Generate event Public datachangedevent producedatachangedevent () {return new Datachangedevent (' This is ChaNged String ");
}
}