EventBus的使用;消息传递之EventBus;

EventBus传递消息(数据)和广播有点像,对广播传递数据有兴趣的可以看一下;Android数据传递,使用广播BroadcastReceiver;

1、添加build.gradle

implementation 'org.greenrobot:eventbus:3.1.1'

好了,引入之后我们就可以愉快的使用eventbus了;

2、在接收消息的界面:MainActivity

注册EventBus接收器:

EventBus.getDefault().register(this);

接收EventBus发送过来的数据:

@Subscribe (threadMode = ThreadMode.MAIN) //主线程接收事件
    public void onEventBus(String msg){
        tv.setText(msg);
    }

作为一个有经验的开发人员,我们一般的都会在界面销毁的时候去反注册一下:

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

下面是MainActivity类中的完整代码;

public class MainActivity extends AppCompatActivity {

    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        tv = findViewById(R.id.tv);
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,InputActivity.class));
            }
        });
    }
    @Subscribe (threadMode = ThreadMode.MAIN) //主线程接收事件
    public void onEventBus(String msg){
        tv.setText(msg);
    }

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

3、发送数据的类:InputActivity;

发送消息:

EventBus.getDefault().post(((EditText)findViewById(R.id.et)).getText().toString());

这样MainActivity中带有@Subscribe注解的onEventBus方法就能接收导数据了;

public class InputActivity extends AppCompatActivity {

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

    public void postMsg(View view) {
        EventBus.getDefault().post(((EditText)findViewById(R.id.et)).getText().toString()
                +"____我就是EventBus发送的消息,是不是接收到很开心呢!!!");
        finish();
    }
}

布局:R.layout.activity_input

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".InputActivity">
    <EditText
        android:id="@+id/et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/et"
        android:text="发送EventBus消息"
        android:onClick="postMsg"
        />
</RelativeLayout>

还有一些粘性消息,切换线程的自己可以去看一下,这只是最简单的使用方法;

猜你喜欢

转载自blog.csdn.net/qq_35605213/article/details/80257574