Event 2.4 跳转接收消息

来源:互联网 发布:树型网络拓扑结构 编辑:程序博客网 时间:2024/06/03 05:37

依赖: (导Event 的 jar包)

compile files('libs/EventBus2.4.jar')

无网络请求

MessageEvent

public class MessageEvent {//类的用途  事件类 用于封装消息    private  String msg;    public MessageEvent(String msg) {        this.msg = msg;    }    public String getMsg() {        return msg;    }    public void setMsg(String msg) {        this.msg = msg;    }}

MainActivity
/** * 订阅消息的页面 */public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //注册EventBus  单例设计模式        EventBus.getDefault().register(this);        findViewById(R.id.bt_jump).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                startActivity(new Intent(MainActivity.this,Main2Activity.class));            }        });    }    /* public void onEvent(MessageEvent event){            Toast.makeText(this, "我接收到了EventBus发送过来的消息", Toast.LENGTH_SHORT).show();        }*/    public  void onEventMainThread(MessageEvent event){        Toast.makeText(this, "我接收到了EventBus发送过来的消息", Toast.LENGTH_SHORT).show();    }    @Override    protected void onDestroy() {        super.onDestroy();        //页面销毁的地方注销掉EventBus        EventBus.getDefault().unregister(this);    }}

xml:
 <Button        android:id="@+id/bt_jump"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="跳转"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintLeft_toLeftOf="parent"        app:layout_constraintRight_toRightOf="parent"        app:layout_constraintTop_toTopOf="parent"/>

Main2Activity:
 <Button        android:id="@+id/bt_jump"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="跳转"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintLeft_toLeftOf="parent"        app:layout_constraintRight_toRightOf="parent"        app:layout_constraintTop_toTopOf="parent"/>

xml2:
 <Button        android:id="@+id/bt_send"        android:text="发送消息"        android:layout_width="wrap_content"        android:layout_height="wrap_content"/>