Simple use of EventBus
// Dependency
// compile 'org.greenrobot:eventbus:3.0.0'
// Main
Package com. example. myeventbus; import android. content. intent; import android. OS. bundle; import android. support. v7.app. appCompatActivity; import android. util. log; import android. view. view; import android. widget. button; import android. widget. textView; import org. greenrobot. eventbus. eventBus; import org. greenrobot. eventbus. subscribe; import org. greenrobot. eventbus. threadMode; public class MainActivity extends PpCompatActivity {Button btn; TextView TV; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); EventBus. getDefault (). register (MainActivity. this); btn = (Button) findViewById (R. id. btn_try); TV = (TextView) findViewById (R. id. TV); btn. setOnClickListener (new View. onClickListener () {@ Override public void onClick (Vi Ew v) {// TODO Auto-generated method stub // the Post method in EventBus is used to send messages. The new class instance is used to send messages! Intent intent = new Intent (MainActivity. this, SecondActivity. class); startActivity (intent) ;}}) ;}// this sentence must be added // we use onEventMainThread (), which is the most commonly used in EventBus () function to receive the message @ Subscribe (threadMode = ThreadMode. MAIN) public void onEventMainThread (FirstEvent event) {String msg = "onEventMainThread received the message:" + event. getMsg (); Log. d ("harvic", msg); TV. setText (msg); // Toast. makeText (this, msg, Toast. LENGTH_LONG ). show () ;}@ Override protected void onDestroy () {super. onDestroy (); EventBus. getDefault (). unregister (this);} // test button public void click (View view) {Intent intent = new Intent (MainActivity. this, CeshiActivity. class); startActivity (intent );}}
// Main layout
// Jump Activity
Package com. example. myeventbus; import android. OS. bundle; import android. support. v7.app. appCompatActivity; import android. view. view; import android. widget. button; import org. greenrobot. eventbus. eventBus; public class SecondActivity extends AppCompatActivity {private Button btn_FirstEvent; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. Layout. activity_second); btn_FirstEvent = (Button) findViewById (R. id. btn_first_event); btn_FirstEvent.setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {// TODO Auto-generated method stub EventBus. getDefault (). post (new FirstEvent ("I'm Eventbus, hello! "); Finish ();}});}}
// Tool class for passing values
public class FirstEvent { private String mMsg; public FirstEvent(String msg) { // TODO Auto-generated constructor stub mMsg = msg; } public String getMsg(){ return mMsg; }}