package com.l.eventbusdemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.squareup.otto.Produce;
import com.squareup.otto.Subscribe;
public class MainActivity extends Activity implements OnClickListener{
private Button btnClose;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//注冊AppEvent
AppEvent.getInstance().register(mEventSubscriber);
initView();
}
private void initView() {
btnClose = (Button) findViewById(R.id.btn_close);
btnClose.setOnClickListener(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
AppEvent.getInstance().unregister(mEventSubscriber);
}
//用來注冊監聽
private Object mEventSubscriber = new Object() {
@Subscribe
public void onHzAppBusEventReceived(AppEventModel event) {
int requestCode = event.getEventCode();
Bundle data = event.getBundle();
OnAppBusEvent(requestCode,data);
}
};
//通過eventCode接收消息
private void OnAppBusEvent(int eventCode,Bundle bundle){
switch(eventCode){
case 0x001:
finish();
break;
}
}
//發送event
private void sendEventBus(int eventCode,Bundle bundle){
AppEvent.getInstance().postQueue(event(eventCode, bundle));
}
@Produce
public static AppEventModel event(int eventCode, Bundle bundle) {
AppEventModel aEvent = new AppEventModel(eventCode);
aEvent.setBundle(bundle);
return aEvent;
}
@Override
public void onClick(View v) {
sendEventBus(0x001, new Bundle());
}
}
MainActivity.class
package com.l.eventbusdemo;
import android.os.Handler;
import android.os.Looper;
import com.squareup.otto.Bus;
public class AppEvent extends Bus {
private static AppEvent instance;
public static AppEvent getInstance() {
if (instance == null)
instance = new AppEvent();
return instance;
}
private Handler mHandler = new Handler(Looper.getMainLooper());
public void postQueue(final Object obj) {
mHandler.post(new Runnable() {
@Override
public void run() {
AppEvent.getInstance().post(obj);
}
});
}
}
AppEvent.class
package com.l.eventbusdemo;
import android.os.Bundle;
public class AppEventModel {
private int eventCode;
private Bundle bundle;
public AppEventModel(int eventCode) {
this.eventCode = eventCode;
}
public int getEventCode() {
return eventCode;
}
public void setEventCode(int eventCode) {
this.eventCode = eventCode;
}
public Bundle getBundle() {
return bundle;
}
public void setBundle(Bundle bundle) {
this.bundle = bundle;
}
}
AppEventModel.class