1,最先在項目中使用EventBus是在去年的時候,但本身一直沒抽出時間來記錄記錄一下,今天就來簡單的使用一下,先看一下EventBus的定義是什麼java
EventBus:是一個發佈 / 訂閱的事件總線。android
再來看看它能幹什麼事 app
主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,線程之間傳遞消息.優勢是開銷小,代碼更優雅。以及將發送者和接收者解耦。ide
咱們來簡單的實現一下其功能吧:post
EventBus的簡單實用就是下面的四個方法this
eventBus.register(this); //添加綁定線程
eventBus.post(Event event); //發送消息給綁定者blog
onEventMainThread(Event event);// 綁定者收到消息的接口回調接口
eventBus.unregister(this); //解除綁定事件
既然知道大體的使用流程就開始咱們的代碼吧
首先添加依賴:
compile 'org.greenrobot:eventbus:3.0.0'
再看看MainActivity.java,SecondActivity.java,就再也不過多的描述了
package com.qianmo.eventbustest; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.qianmo.eventbustest.Event.FirstEvent; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; public class MainActivity extends AppCompatActivity { private Button mFirstButton; private TextView mTextCallBack; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EventBus.getDefault().register(this); mFirstButton = (Button) findViewById(R.id.btn_first); mTextCallBack = (TextView) findViewById(R.id.tv_sendCallBcak); mFirstButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(MainActivity.this, SecondActivity.class)); } }); } @Subscribe public void onEventMainThread(FirstEvent firstEvent) { Toast.makeText(MainActivity.this, firstEvent.getMsg(), Toast.LENGTH_SHORT).show(); mTextCallBack.setText(firstEvent.getMsg()); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } }
package com.qianmo.eventbustest; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import com.qianmo.eventbustest.Event.FirstEvent; import org.greenrobot.eventbus.EventBus; public class SecondActivity extends AppCompatActivity { private Button mSecondButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); mSecondButton = (Button) findViewById(R.id.btn_second); mSecondButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { EventBus.getDefault().post(new FirstEvent("我是界面二")); } }); } }
* 3.0以後在onEventMainThread 上加@Subscribe是必須的