EnentBus进行页面间的传值

EventBus是一款针对Android优化的发布/订阅事件总线。主要功能是替代Intent,Handler,BroadCast
在Fragment,Activity,Service,线程之间传递消息.优点是开销小,代码更优雅。
以及将发送者和接收者解耦。
EventBus的四个接收函数
1、onEvent
2、onEventMainThread
3、onEventBackgroundThread
4、onEventAsync
这四种订阅函数都是使用onEvent开头的,它们的功能稍有不同,在介绍不同之前先介绍两个概念:
告知观察者事件发生时通过EventBus.post函数实现,这个过程叫做事件的发布,观察者被告知事件发生叫做事件的接收,是通过下面的订阅函数实现的。
讲来讲去就是说一个问题:消息的接收是根据参数中的类名来决定执行哪一个的;
参数是那个类就执行那个方法
onEvent:如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。
onEventMainThread:如 果使用onEventMainThread作为订阅函数,那么不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执 行,接收事件就会在UI线程中运行,这个在Android中是非常有用的,因为在Android中只能在UI线程中跟新UI,所以在 onEvnetMainThread方法中是不能执行耗时操作的。
onEventBackground:如果使用onEventBackgrond作为订阅函数,那么如果事件是在UI线程中发布出来的,那么onEventBackground就会在子线程中运行,如果事件本来就是子线程中发布出来的,那么onEventBackground函数直接在该子线程中执行。
onEventAsync:使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync.

1、下载EventBus的类库
源码:https://github.com/greenrobot/EventBus
2、基本使用
(1)自定义一个类,可以是空类,比如:
[java]view plaincopy
public class AnyEventType {  
     public AnyEventType(){}  
 }  
(2)在要接收消息的页面注册:
[java]view plaincopy
eventBus.register(this);  
(3)发送消息
[java]view plaincopy
eventBus.post(new AnyEventType event);  
(4)接受消息的页面实现(共有四个函数,各功能不同,这是其中之一,可以选择性的实现,这里先实现一个):
[java]view plaincopy
 // 订阅消息的方法有4个. 
 // 这个方法用来接受消息:订阅消息. 
    public void onEventMainThread(FristEvent event) { 
         Bitmap bitmap = event.getBitmap(); 
         iv.setImageBitmap(bitmap); 
    } 
   public void onEvent(FristEvent event) {  } 
   public void onEventAsync() {  } 
   public void onEventBackgroundThread() {  }
(5)解除注册
[java]view plaincopy
eventBus.unregister(this);  
顺序就是这么个顺序,可真正让自己写,估计还是云里雾里的,下面举个例子来说明下。
首先,在EventBus中,获取实例的方法一般是采用EventBus.getInstance()来获取默认的EventBus实例,当然你也可以new一个又一个,个人感觉还是用默认的比较好,以防出错。

//第一步 建立要传递的javabean
package com.zhuang.eventbus;
import android.graphics.Bitmap;
      public class FristEvent {
        private Bitmap bitmap;
       public FristEvent(Bitmap bitmap) {
                        this.bitmap = bitmap;
        }
      public Bitmap getBitmap() {
                  return bitmap;
      }
     public void setBitmap(Bitmap bitmap) {
                  this.bitmap = bitmap;
      }
}


//第二步  先将消息发出去
package com.zhuang.eventbus;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.IntentService;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import de.greenrobot.event.EventBus;
public class DownService extends IntentService {
          public DownService() {
              super("");
           }
 @Override
 protected void onHandleIntent(Intent intent) {
  HttpClient client = new DefaultHttpClient();
     HttpGet request = new HttpGet(getResources()  .getString(R.string.img_url)); 
              try {
                       HttpResponse response = client.execute(request);
                        if (response.getStatusLine().getStatusCode() == 200) {
                         byte[] data = EntityUtils.toByteArray(response.getEntity());
                          Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); 
                          // 将bitmap返回到Activity中
                          // 消息发布:
                          EventBus.getDefault().post(new FristEvent(bitmap));
                         }
              } catch (IOException e) {
                 e.printStackTrace();
         }
     }
}
//第三步  注册事件总线,接收这个消息

package com.zhuang.eventbus;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import de.greenrobot.event.EventBus;
public class MainActivity extends Activity {
          private ImageView iv;
         @Override
         protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              iv = (ImageView) findViewById(R.id.iv);
              // 注册事件总线
              EventBus.getDefault().register(this);
         }
         public void down(View v) { 
                  startService(new Intent(this, DownService.class));
         }
            // 订阅消息的方法有4个.
             // 这个方法用来接受消息:订阅消息.
             public void onEventMainThread(FristEvent event) {
                      Bitmap bitmap = event.getBitmap();
                      iv.setImageBitmap(bitmap);
             }
             public void onEvent(FristEvent event) {}
             public void onEventAsync() {}
             public void onEventBackgroundThread() {}

             @Override
             protected void onDestroy() {
              super.onDestroy();
              // 取消事件总线的注册
              EventBus.getDefault().unregister(this);
             }
}

EventBus进阶练习
package com.longyue.eventbushigh;
import de.greenrobot.event.EventBus;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
 private Button btn_FirstEvent, btn_SecondEvent, btn_ThirdEvent;
 @Override
 protected void onResume(){
  super.onResume();
  //注册事件总线
  EventBus.getDefault().register(this);
 }
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  initView();
 }
 public void onEventMainThread(FirstEvent event) {
  Log.e("harvic", "onEventMainThread收到了消息:" + event.getMsg());
 }
 // SecondEvent接收函数一
 public void onEventMainThread(SecondEvent event) {
  Log.e("harvic", "onEventMainThread收到了消息:" + event.getMsg());
 }
 // SecondEvent接收函数二
 public void onEventBackgroundThread(SecondEvent event) {
  Log.e("harvic", "onEventBackground收到了消息:" + event.getMsg());
 }
 // SecondEvent接收函数三
 public void onEventAsync(SecondEvent event) {
  Log.e("harvic", "onEventAsync收到了消息:" + event.getMsg());
 }
 public void onEvent(ThirdEvent event) {
  Log.e("harvic", "OnEvent收到了消息:" + event.getMsg());
 }
 @Override
 protected void onDestroy() {
  super.onDestroy();
  //取消事件总线的注册
  EventBus.getDefault().unregister(this);
 }

 private void initView() {
  btn_FirstEvent = (Button) findViewById(R.id.btn_first_event);
  btn_SecondEvent = (Button) findViewById(R.id.btn_second_event);
  btn_ThirdEvent = (Button) findViewById(R.id.btn_third_event);
  btn_FirstEvent.setOnClickListener(this);
  btn_SecondEvent.setOnClickListener(this);
  btn_ThirdEvent.setOnClickListener(this);
 }
 @Override
 public void onClick(View v) {
  switch (v.getId()) {
  case R.id.btn_first_event:
   EventBus.getDefault().post(new FirstEvent("FirstEvent btn clicked"));
   break;
  case R.id.btn_second_event:
   EventBus.getDefault().post(new SecondEvent("SecondEvent btn clicked"));
   break;
  case R.id.btn_third_event:
   EventBus.getDefault().post(new ThirdEvent("ThirdEvent btn clicked"));
   break;
  }
 }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值