Last active
August 29, 2015 14:18
-
-
Save jayrambhia/096daab360b9250c61e4 to your computer and use it in GitHub Desktop.
EventBus Demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainActivity extends ActionBarActivity { | |
private EventBus eventBus; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
eventBus = EventBus.getDefault(); | |
// Register EventBus | |
eventBus.register(this); | |
} | |
@Override | |
protected void onDestroy() { | |
super.onDestroy(); | |
// Unregister EventBus | |
if (eventBus != null && eventBus.isRegistered(this)) { | |
eventBus.unregister(this); | |
} | |
} | |
public void buttonClicked(View v) { | |
String text = ((EditText)v).getText().toString(); | |
if (!text.isEmpty()) { | |
eventBus.post(new MessageEvent(text)); | |
} | |
} | |
/* subscriber method */ | |
public void onEvent(ResponderService.ServiceMessageEvent event) { | |
String data = event.getMessage(); | |
// do something with this message | |
} | |
public class MessageEvent { | |
private String message; | |
public MessageEvent(String text) { | |
message = text; | |
} | |
public String getMessage() { | |
return message; | |
} | |
public void setMessage(String msg) { message = msg;} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ResponderService extends Service { | |
@Override | |
public IBinder onBind(Intent intent) {return null;} | |
@Override | |
public void onCreate() {} | |
@Override | |
public int onStartCommand(Intent intent, int flags, int startId) { | |
// Register EventBus | |
if (!EventBus.getDefault().isRegistered(this)) { | |
EventBus.getDefault().register(this); | |
} | |
return START_STICKY; | |
} | |
public void onEvent(MessageEvent event) { | |
String message = event.getMessage(); | |
// process data | |
String processed_message = new StringBuilder(event.getMessage()).reverse().toString(); | |
// post : send to activity | |
EventBus.getDefault().post(new ServiceMessageEvent(processed_message)); | |
} | |
@Override | |
public void onDestroy() { | |
super.onDestroy(); | |
// unregister EventBus | |
EventBus.getDefault().unregister(this); | |
} | |
public class ServiceMessageEvent { | |
private String message; | |
public ServiceMessageEvent(String text) { | |
message = text; | |
} | |
public String getMessage() { | |
return message; | |
} | |
public void setMessage(String msg) { message = msg;} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment