
正文
android开源项目之OTTO事件总线(二)官方demo解说
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
官方demo见 https://github.com/square/otto
注意自己该编译版本为2.3以上,默认的1.6不支持match_parent属性,导致布局文件出错。
另外需要手动添加android-support-v4和otto到自己的libs文件夹。
主要代码逻辑:
1,在主页面点clear按钮,发布两个事件并传递对象。
2,然后LocationHistoryFragment接收事件对象,并处理。
1,BusProvider提供一个全局唯一的Bus实例对象
调用的时候使用MyProvider.getBusInstance()
/*
* Copyright (C) 2012 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package com.squareup.otto.sample; import com.squareup.otto.Bus; /**
* Maintains a singleton instance for obtaining the bus. Ideally this would be replaced with a more efficient means
* such as through injection directly into interested classes.
*/
public final class BusProvider {
private static final Bus BUS = new Bus(); public static Bus getInstance() {
return BUS;
} private BusProvider() {
// No instances.
}
}
BusProvider
2,LocationActivity为主页面
点击clear按钮会发布两个事件对象,LocationClearEvent和LocationChangedEvent
findViewById(R.id.clear_location).setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
// Tell everyone to clear their location history.
//清除位置
BusProvider.getInstance().post(new LocationClearEvent()); // Post new location event for the default location.
//重新加载默认的位置
lastLatitude = DEFAULT_LAT;
lastLongitude = DEFAULT_LON;
BusProvider.getInstance().post(produceLocationEvent());
}
});
要使用事件总线别忘了注册和反注册
@Override protected void onResume() {
super.onResume(); // Register ourselves so that we can provide the initial value.
BusProvider.getInstance().register(this);
} @Override protected void onPause() {
super.onPause(); // Always unregister when an object no longer should be on the bus.
BusProvider.getInstance().unregister(this);
}
3,上文提到的事件发送时要传递的两个对象LocationChangedEvent对象和LocationClearEvent
可以根据自己喜好,任意设置对象。代码见demo
4,LocationHistoryFragment里接收事件对象
同样需要注册和反注册。有时我们在服务里发布事件,则无需注册
@Subscribe public void onLocationChanged(LocationChangedEvent event) {
locationEvents.add(, event.toString());
if (adapter != null) {
adapter.notifyDataSetChanged();
}
} @Subscribe public void onLocationCleared(LocationClearEvent event) {
locationEvents.clear();
if (adapter != null) {
adapter.notifyDataSetChanged();
}







