Eventbus基本使用 讲述一些最简单的使用方法 适合新手

首先Eventbus需要的依赖:

implementation 'de.greenrobot:eventbus:3.0.0-beta1'

这个Eventbus用的是一个观察者模式(就是一个订阅关系,你订阅了,就可以收到消息,你没有订阅就收不到消息)

听不太懂么,那么给大家来一个栗子

就是警察和小偷的故事 警察和小偷就是警察看着小偷偷东西,警察就是观察者,小偷就是被观察者

(本人也是一个新手,如果有写的不对的地方 希望大家可以多多探讨)

然后不多比比  直接上代码

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);
    }


    /**
     * 发送事件
     * @param view
     */
    public void click(View view) {


        startActivity(new Intent(this,Main2Activity.class));
        EventBus.getDefault().postSticky(new News("id","100"));






    }


    @Subscribe
    public void accept(String s){


        tv.setText(s);
    }


    @Override
    protected void onDestroy() {

        super.onDestroy();

    //一定要在onDestroy取消订阅,否则可能引起内存泄漏

        EventBus.getDefault().unregister(this);
    }


}


//这个是接收的类

public class Main2Activity extends AppCompatActivity {


    private TextView tv;


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


        tv = findViewById(R.id.tv);

        //订阅
        EventBus.getDefault().register(this);
    }


    /**
     * 发送到act1
     * @param view
     */
    public void click2(View view) {


        EventBus.getDefault().post("hello、 a1");
        finish();


    }


    /**
     * 接收事件的方法:对象,支持粘性事件
     * @param news

     */

    //这边主要是有一个粘性事件

    @Subscribe(sticky = true,threadMode = ThreadMode.Async)
    public void a(News news){
        System.out.println("title"+news.title);
//        try {
//            Thread.sleep(100);
//        } catch (InterruptedException e) {
//            e.printStackTrace();

//        }

//给控件赋值

        tv.setText(news.desc);

        System.out.println("threadname:"+Thread.currentThread().getName());


    }


    @Subscribe
    public void b(String s){
        System.out.println("s:"+s);
    }


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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值