//导入依赖
compile 'org.greenrobot:eventbus:3.0.0'
MainActivity
package bwie.com.eventbus;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
public class MainActivity extends AppCompatActivity {
private Button btn;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//注册(在接收消息的页面进行注册)
EventBus.getDefault().register(this);
btn = (Button) findViewById(R.id.btn);
tv = (TextView) findViewById(R.id.tv);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),SecodeActivity.class);
startActivity(intent);
}
});
}
//设置订阅者(如果出不来加 Sticky=true)
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(FirstEvent event) {
String msg = "onEventMainThread收到了消息:" + event.getMsg();
// Log.d("harvic", msg);
tv.setText(msg);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
解除注册
@Override
protected void onDestroy() {
super.onDestroy();
//反注册EventBus
EventBus.getDefault().unregister(this);
}
}
//新建一个类FirstEvent
package bwie.com.eventbus;
public class FirstEvent {
private String msg;
public FirstEvent(String msg) {
this.msg = msg;
}
public String getMsg(){
return msg;
}
}
//回传消息
SecodeActivity
package bwie.com.eventbus;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import org.greenrobot.eventbus.EventBus;
public class SecodeActivity extends AppCompatActivity {
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_secode);
btn = (Button) findViewById(R.id.frist_btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EventBus.getDefault().post(new FirstEvent("你好,世界"));
}
});
}
}