首先加入EventBus的依賴android
1 compile 'de.greenrobot:eventbus:3.0.0-beta1' app
EventBus代碼實現ide
1 import android.content.Intent; 2 import android.support.v7.app.AppCompatActivity; 3 import android.os.Bundle; 4 import android.view.View; 5 import android.widget.TextView; 6 7 import de.greenrobot.event.EventBus; 8 import de.greenrobot.event.Subscribe; 9 import de.greenrobot.event.ThreadMode; 10 11 public class MainActivity extends AppCompatActivity { 12 private TextView tv; 13 @Override 14 protected void onCreate(Bundle savedInstanceState) { 15 super.onCreate(savedInstanceState); 16 setContentView(R.layout.activity_main); 17 tv= (TextView) findViewById(R.id.tv); 18 EventBus.getDefault().register(this);//註冊EventBus 19 } 20 21 public void onClick(View view) { 22 Intent intent=new Intent(this,Main2Activity.class); 23 startActivity(intent); 24 }
//接受EventBus傳遞的消息 25 @Subscribe(threadMode= ThreadMode.MainThread) 26 public void getMessage(String string){ 27 tv.setText(string); 28 } 29 }
1 import android.support.v7.app.AppCompatActivity; 2 import android.os.Bundle; 3 import android.view.View; 4 5 import de.greenrobot.event.EventBus; 6 7 public class Main2Activity extends AppCompatActivity { 8 9 @Override 10 protected void onCreate(Bundle savedInstanceState) { 11 super.onCreate(savedInstanceState); 12 setContentView(R.layout.activity_main2); 13 } 14 15 public void onClick(View view) { 16 EventBus.getDefault().post("我是第二個頁面發送的消息"); 17 } 18 }
使用EventBus在那個類接收消息就在那個類中註冊post