您的位置:首页 > 其它

EventBus的使用

2015-01-31 23:12 169 查看
EventBus 这里我就不介绍了,百度 google 一大把,自己找去。这里主要讲下简单的用法,当然也是核心用法,掌握了我所说的这几种用法,基本上就能满足我们项目中的需求了。

源码地址 :https://github.com/greenrobot/EventBus

基本使用原则,分四步吧,第一步:注册 EventBus.getDefault().register(this);-------获取到 EventBus 的实例,把当前类传入。

第二步:发送事件 EventBus.getDefault().post(param1 + param2);

第三步:接收事件 onEvent(param1 + param2)

第四步:注销EventBus.getDefault().unregister(this);

ok 基本使用就是这些,也许有的人看了这四步还是不知道怎么用,那就直接上代码吧,

package com.test.gyzhong.eventbus;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import de.greenrobot.event.EventBus;

public class MainActivity extends ActionBarActivity {

    private TextView mShowTxt ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mShowTxt = (TextView) findViewById(R.id.id_show);
        //启动 一个 intentService
        EventIntentService.startActionFoo(this,"hello"," world !");
    }

    /**
     * 注意此方法必须是 onEvent,并且只能是 public 声明,
     * 不能为 static 声明,参数必须与 post 的参数一致,否
     * 则无法接收到,如果你想改成你喜欢的方法名,可以修改Event
     * 源码,当然,不建议修改,我们应该尊重别人的劳动成果。
     * @param msg
     */
    public void onEvent(String msg){
        Log.v("zgy", "=========msg=====" + msg) ;
    }

    @Override
    protected void onPause() {
        EventBus.getDefault().unregister(this);
        super.onPause();
    }

    @Override
    protected void onResume() {
        EventBus.getDefault().register(this);
        super.onResume();
    }
}


以上代码实现了注册和注销,还有接收事件的操作,那么还需要发送事件的操作,EventBus.getDefault().post(String msg);

我们可以在本类中发送,当然这样也就没有意义了。所以我特意写了一个服务,在服务中向此类中发送事件,ok,贴代码

package com.test.gyzhong.eventbus;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.util.Log;

import de.greenrobot.event.EventBus;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p/>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class EventIntentService extends IntentService {
    // TODO: Rename actions, choose action names that describe tasks that this
    // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
    private static final String ACTION_FOO = "com.test.gyzhong.eventbus.action.FOO";

    // TODO: Rename parameters
    private static final String EXTRA_PARAM1 = "com.test.gyzhong.eventbus.extra.PARAM1";
    private static final String EXTRA_PARAM2 = "com.test.gyzhong.eventbus.extra.PARAM2";

    /**
     * Starts this service to perform action Foo with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    // TODO: Customize helper method
    public static void startActionFoo(Context context, String param1, String param2) {
        Intent intent = new Intent(context, EventIntentService.class);
        intent.setAction(ACTION_FOO);
        intent.putExtra(EXTRA_PARAM1, param1);
        intent.putExtra(EXTRA_PARAM2, param2);
        context.startService(intent);
    }

    public EventIntentService() {
        super("EventIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_FOO.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                handleActionFoo(param1, param2);
            }
        }
    }

    /**
     * Handle action Foo in the provided background thread with the provided
     * parameters.
     */
    private void handleActionFoo(String param1, String param2) {
        // TODO: Handle action Foo

        Log.v("zgy", "======handleActionFoo========") ;
        //在这里向已经注册的类中发送事件,并传递了一个参数
        EventBus.getDefault().post(param1 + param2);
    }

}


全部代码已经贴出来了,有兴趣的可以运行下看下结果,不用运行也猜到了,那就是会在 onEvent 方法中打印出 msg 的值,是多少呢,当然是我们传进去的 hello world !。

是不是很方便?以往我们要在 Activity 和 Service 之间的通信我们会通过广播实现,而现在,我们没有广播同样能实现。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: