星空网 > 软件开发 > 操作系统

EventBus的使用

前言:第一篇文章,EventBus很多项目都在用,本文参照http://blog.csdn.net/harvic880925/article/details/40660137,自己做了一遍。把有用的挑拣出来,记录一下啊

一、概述

EventBus是一款针对Android优化的发布/订阅事件总线。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息.优点是开销小,代码更优雅。以及将发送者和接收者解耦。
1、下载EventBus的类库
源码:https://github.com/greenrobot/EventBus

2、基本使用

(1)自定义一个类,可以是空类,比如:

  public class AnyEventType {      public AnyEventType(){}    } 

 

(2)在要接收消息的页面注册:

eventBus.register(this); 

 

(3)发送消息

eventBus.post(new AnyEventType event); 

 


(4)接受消息的页面实现(共有四个函数,各功能不同):

public void onEvent(AnyEventType event) {} public void onEventMainThread(AnyEventType event) {} public void onEventBackgroundThread(AnyEventType event) {} public void onEventAsync(AnyEventType event) {} 

 


onEvent:如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。
onEventMainThread:如果使用onEventMainThread作为订阅函数,那么不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执行,接收事件就会在UI线程中运行,这个在Android中是非常有用的,因为在Android中只能在UI线程中跟新UI,所以在onEvnetMainThread方法中是不能执行耗时操作的。
onEventBackground:如果使用onEventBackgrond作为订阅函数,那么如果事件是在UI线程中发布出来的,那么onEventBackground就会在子线程中运行,如果事件本来就是子线程中发布出来的,那么onEventBackground函数直接在该子线程中执行。
onEventAsync:使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync.

(5)解除注册

eventBus.unregister(this);

 

顺序就是这么个顺序,可真正让自己写,估计还是云里雾里的,下面举个例子来说明下。

首先,在EventBus中,获取实例的方法一般是采用EventBus.getInstance()来获取默认的EventBus实例,当然你也可以new一个又一个,个人感觉还是用默认的比较好,以防出错。

二、实战

先给大家看个例子:

当击跳转到第二个界面按钮的时候,跳到第二个Activity,当点击第二个activity上面的t按钮的时候向第一个Activity发送消息,第一个按钮使用的是
新建一个Activity,SecondActivity布局(activity_two.

<??><RelativeLayout ="http://schemas.android.com/apk/res/android"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:paddingBottom="@dimen/activity_vertical_margin"  android:paddingLeft="@dimen/activity_horizontal_margin"  android:paddingRight="@dimen/activity_horizontal_margin"  android:paddingTop="@dimen/activity_vertical_margin">  <Button    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:text="@string/bt_text_post"    android:id="@+id/bt_post"/>  <Button    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:text="@string/bt_text_post2"    android:layout_below="@id/bt_post"    android:id="@+id/bt_post2"/></RelativeLayout>

 


MainActivity.java

package com.nova.eventbus_1;import android.content.Intent;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;import org.greenrobot.eventbus.EventBus;import org.greenrobot.eventbus.Subscribe;public class MainActivity extends AppCompatActivity {  private Button button_jump;  private TextView tv_notify;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    button_jump= (Button) findViewById(R.id.bt_jump);    tv_notify= (TextView) findViewById(R.id.tv_notify);    button_jump.setOnClickListener(new View.OnClickListener() {      @Override      public void onClick(View v) {        <strong> Intent intent=new Intent(MainActivity.this,SecondActivity.class);        startActivityForResult(intent,1);</strong>      }    });  }  @Override  protected void onActivityResult(int requestCode, int resultCode, Intent data) {    switch (requestCode){      case 1:        if(resultCode==1){          String returnedData=data.getStringExtra("com.nova.eventbus_1.data_return");          tv_notify.setText(returnedData);          Toast.makeText(MainActivity.this,returnedData,Toast.LENGTH_LONG).show();          Log.i("现在的线程",Thread.currentThread().getName());        }    }  }}

 

SecondActivity.java

 

package com.nova.eventbus_1;import android.content.Intent;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import org.greenrobot.eventbus.EventBus;/** * Created by Nova on 2016/4/11. */public class SecondActivity extends AppCompatActivity {  private Button button_post;  private Button button_post2;//使用EventBus传递  @Override  protected void onCreate(@Nullable Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_two);    button_post= (Button) findViewById(R.id.bt_post);    button_post2= (Button) findViewById(R.id.bt_post2);    button_post.setOnClickListener(new View.OnClickListener() {      @Override      public void onClick(View v) {        Intent intent=new Intent();        intent.putExtra("com.nova.eventbus_1.data_return","跳转按钮:被点击了");        setResult(1,intent);        finish();      }    });     }}

 

 

2、新建一个类FirstEvent

package com.nova.eventbus_1;/** * Created by Nova on 2016/4/12. * cnhjj2008@gmail.com */public class FirstEvent {  private String mMsg;  public FirstEvent(String mMsg) {    this.mMsg = mMsg;  }  public String getMsg() {    return mMsg;  }}

 

 

3、在要接收消息的页面注册EventBus:

在上面的GIF图片的演示中,大家也可以看到,我们是要在MainActivity中接收发过来的消息的,所以我们在MainActivity中注册消息。

通过我们会在OnCreate()函数中注册EventBus,在OnDestroy()函数中反注册。所以整体的注册与反注册的代码如下:

package com.nova.eventbus_1;import android.content.Intent;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;import org.greenrobot.eventbus.EventBus;import org.greenrobot.eventbus.Subscribe;public class MainActivity extends AppCompatActivity {  private Button button_jump;  private TextView tv_notify;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    <strong> //注册EventBus    EventBus.getDefault().register(MainActivity.this);</strong>    button_jump= (Button) findViewById(R.id.bt_jump);    tv_notify= (TextView) findViewById(R.id.tv_notify);    button_jump.setOnClickListener(new View.OnClickListener() {      @Override      public void onClick(View v) {        Intent intent=new Intent(MainActivity.this,SecondActivity.class);        startActivityForResult(intent,1);      }    });  }  @Override  protected void onActivityResult(int requestCode, int resultCode, Intent data) {    switch (requestCode){      case 1:        if(resultCode==1){          String returnedData=data.getStringExtra("com.nova.eventbus_1.data_return");          tv_notify.setText(returnedData);          Toast.makeText(MainActivity.this,returnedData,Toast.LENGTH_LONG).show();          Log.i("现在的线程",Thread.currentThread().getName());        }    }  }  @Subscribe  public void onEventMainThread(FirstEvent event){    String msg="onEventMainThread收到了消息:" + event.getMsg();    tv_notify.setText(msg);    Toast.makeText(MainActivity.this,msg,Toast.LENGTH_LONG).show();    Log.i("现在的线程",Thread.currentThread().getName());  }    @Override  protected void onDestroy() {    super.onDestroy();    <strong>EventBus.getDefault().unregister(MainActivity.this);</strong>  }}

 

 

4、发送消息

发送消息是使用EventBus中的Post方法来实现发送的,发送过去的是我们新建的类的实例!

EventBus.getDefault().post(new FirstEvent("跳转按钮:被点击了EventBus post"));

 

完整的SecondActivity.java的代码如下:

package com.nova.eventbus_1;import android.content.Intent;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import org.greenrobot.eventbus.EventBus;/** * Created by Nova on 2016/4/11. */public class SecondActivity extends AppCompatActivity {  private Button button_post;  private Button button_post2;//使用EventBus传递  @Override  protected void onCreate(@Nullable Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_two);    button_post= (Button) findViewById(R.id.bt_post);    button_post2= (Button) findViewById(R.id.bt_post2);    button_post.setOnClickListener(new View.OnClickListener() {      @Override      public void onClick(View v) {        Intent intent=new Intent();        intent.putExtra("com.nova.eventbus_1.data_return","跳转按钮:被点击了");        setResult(1,intent);        finish();      }    });    button_post2.setOnClickListener(new View.OnClickListener() {      @Override      public void onClick(View v) {        //EventBus使用方法        EventBus.getDefault().post(new FirstEvent("跳转按钮:被点击了EventBus post"));        finish();      }    });  }}

 



5、接收消息

接收消息时,我们使用EventBus中最常用的onEventMainThread()函数来接收消息,具体为什么用这个,我们下篇再讲,这里先给大家一个初步认识,要先能把EventBus用起来先。

在MainActivity中重写onEventMainThread(FirstEvent event),参数就是我们自己定义的类:

在收到Event实例后,我们将其中携带的消息取出,一方面Toast出去,一方面传到TextView中;

@Subscribe  public void onEventMainThread(FirstEvent event){    String msg="onEventMainThread收到了消息:" + event.getMsg();    tv_notify.setText(msg);    Toast.makeText(MainActivity.this,msg,Toast.LENGTH_LONG).show();    Log.i("现在的线程",Thread.currentThread().getName());  }

 


切记一定在开头写上@Subscribe,不然报错。

程序结束。

 




原标题:EventBus的使用

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

怎么下载tiktok的视频:https://www.goluckyvip.com/tag/82208.html
ios如何下载tiktok:https://www.goluckyvip.com/tag/82209.html
Lazada新动态:https://www.goluckyvip.com/tag/8221.html
tiktok安卓直装版:https://www.goluckyvip.com/tag/82210.html
安卓tiktok加速器:https://www.goluckyvip.com/tag/82211.html
tiktok国际版国内可用下载:https://www.goluckyvip.com/tag/82212.html
37号文今后是否会更新?一文详解关键信息 :https://www.kjdsnews.com/a/1836441.html
探讨内地人开设香港账户的可行性 :https://www.kjdsnews.com/a/1836442.html
相关文章
我的浏览记录
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流