'eventbus黏性事件'

package com.www.eventbussticky;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Button btn;
private TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
}

private void initView() {
    btn = (Button) findViewById(R.id.btn);
    tv = (TextView) findViewById(R.id.tv);

    btn.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn:
            startActivity(new Intent(MainActivity.this,SecondActivity.class));
            EventBus.getDefault().postSticky(new MessageEvent("黏性事件"));
            break;
    }
}

}

package com.www.eventbussticky;
public class MessageEvent {
private String message;

public MessageEvent(String message) {
    this.message = message;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

}

package com.www.eventbussticky;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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 SecondActivity extends AppCompatActivity implements View.OnClickListener {

private Button btn;
private TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    initView();
}

private void initView() {
    btn = (Button) findViewById(R.id.btn);
    tv = (TextView) findViewById(R.id.tv);
    btn.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn:
            if(!(EventBus.getDefault().isRegistered(this))){
                EventBus.getDefault().register(this);
            }
            break;
    }
}
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
public void sjx(MessageEvent messageEvent){
    tv.setText(messageEvent.getMessage());
}

@Override
protected void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().unregister(this);
}

}

你可能感兴趣的:('eventbus黏性事件')