EventBus的初级使用技巧

第一次写博客,不知道怎么写,也不知道写些什么,想来想去,写一些自己正在写的音乐播放器的知识吧!!!

今天写EventBus,之前我在Service和Activity之间的传值使用的是接口回调的方式,也可以运行.但是后来老师告诉我说这种方式会导致栈溢出,推荐我使用EventBus方式,代码简单,还很方便.所以我就上网查询了EventBus的使用方法,整理出来,以后想用的时候可以直接看偷笑

1.首先我使用的开发工具是Android Studio 非常好用的开发安卓的工具.,新建一个项目叫做EventBusDemo,在Android Studio中Gradle Scripts中的build.grade(Module:app)中的dependencies里面添加一段代码:

compile 'org.greenrobot:eventbus:3.0.0'
之后重新编译一下,studio中就有EventBus的依赖了.

2.然后在activity_main中添加一个button和textview:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_get"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="btn_get" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="1111"
        android:textColor="#000000"
        />
</LinearLayout>
3.然后在新建一个SecondActivity,在其布局文件activity_second中添加一个button

<Button
    android:id="@+id/btn_send"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Btn_Send" />
4.MainActivity.java跳转到SecondActivity

public class MainActivity extends AppCompatActivity {
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          

        button = (Button) findViewById(R.id.btn_get);
        

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),
                        SecondActivity.class);
                startActivity(intent);
            }
        });
    }
}
5.然后新建一个类EventInfo,这个类很简单,构造时传进去一个字符串,然后可以通过getMsg()获取出来。

public class EventInfo {

    private String Msg;
    public EventInfo(String msg) {
        Msg = msg;
    }
    public String getMsg(){
        return Msg;
    }
}
6.我们在MainActivity中点击button跳转到SecondActivity,然后点击SecondActivity中的button将值传回MainActivity.我们是要在MainActivity中接收发过来的消息的,所以我们先在MainActivity中注册消息。

public class MainActivity extends AppCompatActivity {
    Button button;
    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
           //注册EventBus
        EventBus.getDefault().register(this);

        button = (Button) findViewById(R.id.btn_try);
        tv = (TextView) findViewById(R.id.tv);
        tv.setText("lll");

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),
                        SecondActivity.class);
                startActivity(intent);
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册EventBus
    }
}

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

SecondActivity.java中的代码为:

public class SecondActivity extends AppCompatActivity {
    Button btn_FirstEvent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        btn_FirstEvent = (Button) findViewById(R.id.btn_send);
        btn_FirstEvent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new EventInfo("EventInfo btn clicked"));
            }
        });
    }
}

8.接收消息时,我们使用EventBus中最常用的onEventMainThread()函数来接收消息,

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

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

 @Subscribe
    public void onEventMainThread(FirstEvent event){
        String msg = "onEventMainThread接收到了消息:" + event.getMsg();
        Log.d("HMC", msg);
        tv.setText(msg);
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
完整的MainActivity.java代码如下:

public class MainActivity extends AppCompatActivity {
    Button button;
    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
           //注册EventBus
        EventBus.getDefault().register(this);

        button = (Button) findViewById(R.id.btn_get);
        tv = (TextView) findViewById(R.id.tv);
        tv.setText("lll");

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),
                        SecondActivity.class);
                startActivity(intent);
            }
        });
    }

    @Subscribe
    public void onEventMainThread(EventInfo event){
        String msg = "onEventMainThread接收到了消息:" + event.getMsg();
        Log.d("HMC", msg);
        tv.setText(msg);
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册EventBus
    }
}

首先注意在OnCreate中注册EventBus后下面就有OnDestory来进行反注册EventBus.我刚才运行Demo程序一直崩,后来看Error后在

onEventMainThread
上面添加了
@Subscribe

就好了....


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Vue 中,你可以使用事件总线(Event Bus)来实现组件之间的通信。事件总线是一个空的 Vue 实例,可以用于触发和监听自定义事件。 首先,在你的项目中创建一个新的 Vue 实例作为事件总线: ```javascript // eventBus.js import Vue from 'vue'; export const eventBus = new Vue(); ``` 然后,在需要通信的组件中,你可以使用事件总线来触发事件或监听事件: ```javascript // ComponentA.vue import { eventBus } from './eventBus.js'; export default { methods: { sendMessage() { eventBus.$emit('message', 'Hello from Component A!'); } } } ``` ```javascript // ComponentB.vue import { eventBus } from './eventBus.js'; export default { data() { return { receivedMessage: '' }; }, mounted() { eventBus.$on('message', (message) => { this.receivedMessage = message; }); } } ``` 在上面的示例中,ComponentA 在方法中通过 `eventBus.$emit` 触发了名为 `message` 的自定义事件,并传递了消息内容。而 ComponentB 在 `mounted` 钩子函数中通过 `eventBus.$on` 监听了 `message` 事件,当事件触发时会执行回调函数并将消息内容赋值给 `receivedMessage`。 这样,ComponentA 和 ComponentB 之间就可以通过事件总线进行通信了。请确保在不需要通信时及时销毁事件监听,以避免内存泄漏。 注意:事件总线在组件之间是全局共享的,可以用于任意组件之间的通信。但是如果你的项目越来越复杂,建议考虑使用更好的状态管理方案,如 Vuex。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值