依赖:
compile 'org.greenrobot:eventbus:3.0.0'
首先创建一个实体类:
package wld.bawei.com.myeventbussticky;
/**
* Created by 大金鑫 on 2017/12/27.
*/
public class EventBusStickyMessage {
public String string;
public EventBusStickyMessage(String string){
this.string=string;
}
}
Main1:
package wld.bawei.com.myeventbussticky;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import org.greenrobot.eventbus.EventBus;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//发送
public void Fs(View view){
//要传递的消息
EventBus.getDefault().postSticky(new EventBusStickyMessage("这是一个消西"));
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
}
Main2:
package wld.bawei.com.myeventbussticky;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
public class Main2Activity extends AppCompatActivity {
private TextView tv;
boolean flag= true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
tv = (TextView) findViewById(R.id.tv);
}
public void Js(View view){
if(flag){
EventBus.getDefault().register(this);
flag = false;
}
}
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
public void ReceviceMessage(EventBusStickyMessage eventBusStickyMessage){
tv.setText(eventBusStickyMessage.string);
}
@Override
protected void onDestroy() {
//移除所有的粘性事件
EventBus.getDefault().removeAllStickyEvents();
//解除注册
EventBus.getDefault().unregister(this);
super.onDestroy();
}
}