gpt4 book ai didi

android - 相当于Android中的iOS NSNotificationCenter?

转载 作者:技术小花猫 更新时间:2023-10-29 10:13:17 24 4
gpt4 key购买 nike

在 Android 中是否有等效的 iOS 类 NSNotificationCenter?是否有任何库或有用的代码可供我使用?

最佳答案

Android 没有像 ios 那样的中央通知中心。但是你基本上可以使用 ObservableObserver目标来完成你的任务。

您可以像下面这样定义一个类,只需修改它以供单例使用并添加同步以供并发使用,但思想是相同的:

public class ObservingService {
HashMap<String, Observable> observables;

public ObservingService() {
observables = new HashMap<String, Observable>();
}

public void addObserver(String notification, Observer observer) {
Observable observable = observables.get(notification);
if (observable==null) {
observable = new Observable();
observables.put(notification, observable);
}
observable.addObserver(observer);
}

public void removeObserver(String notification, Observer observer) {
Observable observable = observables.get(notification);
if (observable!=null) {
observable.deleteObserver(observer);
}
}

public void postNotification(String notification, Object object) {
Observable observable = observables.get(notification);
if (observable!=null) {
observable.setChanged();
observable.notifyObservers(object);
}
}
}

关于android - 相当于Android中的iOS NSNotificationCenter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10327200/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com