EventBus.getDefault().post()

EventBusPostActivity向已启动的FirstActivity发送post

流程:FirstActivity启动EventBusPostActivity,然后EventBusPostActivity向FirstActivity发送EventBus关闭FirstActivity

依赖

implementation 'org.greenrobot:eventbus:3.0.0'

序列化基类

public class BaseEntity implements Serializable {

}

代码混淆

#EventBus
-keepattributes *Annotation*
-keepclassmembers class ** {
    @org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }

#实体类
-keep class * extends 包名.BaseEntity{*;}

实体类

public class EventBusEntity extends BaseEntity {

    public static final int TYPE_EVENT_BUS_POST = 1001;

    private int eventType;
    private String eventMessage;

    public EventBusEntity(int eventType, String eventMessage) {
        this.eventType = eventType;
        this.eventMessage = eventMessage;
    }

    public int getEventType() {
        return eventType;
    }

    public void setEventType(int eventType) {
        this.eventType = eventType;
    }

    public String getEventMessage() {
        return eventMessage;
    }

    public void setEventMessage(String eventMessage) {
        this.eventMessage = eventMessage;
    }
}

FirstActivity

public class FirstActivity extends AppCompatActivity {

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

        //注册EventBus
        EventBus.getDefault().register(this);

        
        findViewById(R.id.id_btn_post).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(FirstActivity.this, EventBusPostActivity.class));
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventBusEntity entity) {
        if (entity.getEventType() == EventBusEntity.TYPE_EVENT_BUS_POST) {
            String msg = entity.getEventMessage();
            Log.i("TAG", "------ post message : " + msg);
            finish();
        }
    }


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

}

EventBusPostActivity

public class EventBusPostActivity extends AppCompatActivity {

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


        findViewById(R.id.id_btn_ppp).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EventBus.getDefault().post(new EventBusEntity(EventBusEntity.TYPE_EVENT_BUS_POST, "finish()"));
            }
        });
    }
}

你可能感兴趣的:(Android,Learning,android)