EventBus和otto消息机制在Android Studio中的简单使用

EventBus使用

1.在build.gradle文件中配置

compile 'org.greenrobot:eventbus:3.0.0'

2.在SecondActivity中注册(注意在栈中只能从栈顶的Activity往下发面的Activity发送消息)

EventBus.getDefault().post("haha");

3.在MainActivity中接收消息

EventBus.getDefault().register(this);
//方法权限必须是public
@Subscribe
public void showText(String str){
    Log.v("m520","接收到了"+str);
    tv_msg.setText(str);

}

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

Otto消息机制

1.在build.gradle文件中配置

compile 'com.squareup:otto:+'

2.创建一个类AppBus继承Bus并封装成单例

public class AppBus extends Bus {

private AppBus(){}
private static  AppBus bus;
public static AppBus getInstance(){
    if (bus==null){
        bus=new AppBus();
    }
    return bus;
}
}

3.在SecondActivity获取AppBus对象实例并发送消息

public class SecondActivity extends Activity {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    AppBus bus = AppBus.getInstance();
    bus.post(new MyEvnt("小明",18));
}

public class MyEvnt {
    String name;
    int age;

    public MyEvnt(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}
    }

4.在MainActivity中注册接收消息

public class MainActivity extends AppCompatActivity {

TextView tv_sendmsg;
AppBus bus;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bus = AppBus.getInstance();
    bus.register(this);
    tv_sendmsg=(TextView)findViewById(R.id.tv_sendmsg);

}

public void textClick(View v){
    startActivity(new Intent(this,SecondActivity.class));
}

@Subscribe
public void answerAvailable(SecondActivity.MyEvnt str) {
    Log.v("m520","MyEvnt="+str.getName()+"...."+str.getAge());

}

@Override
protected void onDestroy() {
    super.onDestroy();
    bus.unregister(this);

}
}

以下github地址可供参考

https://github.com/greenrobot/EventBus
https://github.com/square/otto

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值