iOS的NSNotificationCenter在Android的相同呢? [英] Equivalent of iOS NSNotificationCenter in Android?

查看:405
本文介绍了iOS的NSNotificationCenter在Android的相同呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有iOS的类NSNotificationCenter Android中的等效?是否有任何可用的库或用code对我?

Is there an equivalent of the iOS class NSNotificationCenter in Android ? Are there any libraries or useful code available to me ?

推荐答案

在Android中没有一个中央通知中心的IOS。 但是,你基本上可以使用观测和的观察对象来实现你的任务。

In Android there is not a central notification center as in ios. But you can basically use Observable and Observer objects to achieve your task.

您可以定义一个类象下面这样的东西,只是修改了单使用和同时使用加同步,但这个想法是一样的:

You can define a class like something below, just modify it for singleton use and add synchronized for concurrent use but the idea is the same:

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);
        }
    }
}

这篇关于iOS的NSNotificationCenter在Android的相同呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆