有没有办法在一个班级中为所有活动举办活动?
实际上我正在使用自定义侦听器并在某处注册它们。但我知道我是否可以抛出一个像“newMessageEvent”或类似的自定义事件,并在每个活着的活动中接收它。
我使用的是好方法还是存在更好的方式?
有人知道吗?
答案 0 :(得分:0)
很久以前回答我自己提出的问题,如果有人需要它,可以提供一个有效的解决方案:
1-创建一个Singleton类来管理这样的事件:
public class EventsManager {
public enum EventType{
//Define here your types
}
public interface EventsManagerListener{
void onEvent(EventType eventType);
}
private static EventsManager instance;
private HashMap<EventType,List<EventsManagerListener>> listenersMap;
private EventsManager(){
listenersMap = new HashMap<>();
}
public static EventsManager getInstance(){
if(instance == null){
instance = new EventsManager();
}
return instance;
}
public void registerForEvent(EventType eventType, EventsManagerListener listener ){
List<EventsManagerListener> eventListeners = listenersMap.get(eventType);
if(eventListeners == null){
eventListeners = new ArrayList<>();
listenersMap.put(eventType,eventListeners);
}
if(!eventListeners.contains(listener)) {
eventListeners.add(listener);
}
}
public void unregisterForEvent(EventType eventType, EventsManagerListener listener){
List<EventsManagerListener> eventListeners = listenersMap.get(eventType);
if(eventListeners != null){
eventListeners.remove(listener);
}
}
public void throwEvent(EventType eventType){
List<EventsManagerListener> eventListeners = listenersMap.get(eventType);
if(eventListeners != null){
//This iteration sends the event to the newest activity first
for(int i = eventListeners.size()-1; i >= 0; i--){
EventsManagerListener listener = eventListeners.get(i);
listener.onEvent(eventType);
}
}
}
}
2-子类活动(例如MyBaseActivity)
public class MyBaseActivity extends Activity{
}
3-覆盖onCreate和onDestroy方法并调用事件管理器并使活动实现EventsManagerListener
public class MyBaseActivity extends Activity implements EventsManagerListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
EventsManager.getInstance().registerForEvent(THE_EVENT_YOU_WANT, this);
}
@Override
protected void onDestroy(Bundle savedInstanceState) {
super.onDestroy(savedInstanceState);
//...
EventsManager.getInstance().unregisterForEvent(THE_EVENT_YOU_WANT, this);
}
public void onEvent(EventsManager.EventType eventType){
//... handle the event
}
}
4-最后,您必须在下一行调用您要发送该事件的位置:
EventsManager.getInstance().throwEvent(YOUR_EVENT);
希望有所帮助!