zoukankan      html  css  js  c++  java
  • EventBus的使用

    观察者与被观察者的模式,类似于RXJava。首先,去GitHub上搜索,然后直接官方文档直接建议可以Gradle引入:在app.Gradle中加入   

    //EventBus
        compile 'de.greenrobot:eventbus:2.4.0'

    在SecondActivity中发送对象到MainActivity

    这是MainActivity:

    public class MainActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            //注册EventBus
            EventBus.getDefault().register(MainActivity.this);
    
    
        }
      //跳转到第二个Activity
    public void click(View v){ startActivity(new Intent(MainActivity.this,SecondActivity.class)); } @Override protected void onDestroy() { super.onDestroy(); //解除注册EventBus EventBus.getDefault().unregister(MainActivity.this); } //写这个方法用来接受对象,onEventMainThread表示不管信息从哪发过来,接受事件都在主线程 public void onEventMainThread(String s) { Log.d("msg","当前线程--->"+Thread.currentThread().getName()); Log.d("msg", "MainActivity收到消息-->" + s); } }

    第二个Activity:

    /**点击按钮发送事件
     * Created by xhj on 16-1-13.
     */
    public class SecondActivity extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_second);
            Button btnSend= (Button) findViewById(R.id.btnSend);
            btnSend.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.d("msg", "SecondActivity当前线程--->"+Thread.currentThread().getName());
                    EventBus.getDefault().post("hahahhahaa");//EventBus发送事件(对象)
                }
            });
    
        }
    }

     EventBus不能注册多次,注册多次就会多次接收事件

    这里有一片文章已经总结的很好了 ,http://blog.csdn.net/harvic880925/article/details/40660137

  • 相关阅读:
    .Net EF中DbContext动态生成DbSet
    .net core 3.0 中间件或过滤器中读取post请求body方法
    Asp.Net Core 5 WebAPI发布后的Swagger不显示问题
    .net Core 使用Swagger 让某些接口不显示在文档
    C# Request.InputStream 读取输入流为空的原因处理
    ASP.NET 中的缓存
    缓存依赖(文件、数据库)
    NLTK基本使用
    NLTK基本使用
    NLTK的基本使用
  • 原文地址:https://www.cnblogs.com/android-yus/p/5127364.html
Copyright © 2011-2022 走看看