All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.yy.androidlib.util.notification.Notification Maven / Gradle / Ivy

There is a newer version: 1.1.4
Show newest version
package com.yy.androidlib.util.notification;

import android.os.Handler;
import android.util.Log;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Notification implements InvocationHandler {
    private Map observers;
    private Handler mainHandler;
    private T observerProxy = null;
    private Class callback;

    public Notification(Class callback, Handler handler) {
        this.callback = callback;
        this.mainHandler = handler;
        this.observers = new ConcurrentHashMap<>();
    }

    public Object invoke(Object proxy, final Method method, final Object[] args) {
        mainHandler.post(new Runnable() {
            public void run() {
                doInvoke(method, args);
            }
        });
        return null;
    }

    private void doInvoke(Method method, Object[] args) {
        for (Object observer : observers.keySet()) {
            try {
                method.invoke(observer, args);
            } catch (Exception e) {
                Log.e(NotificationCenter.TAG, "invoke error, method: " + method.getName(), e);
            }
        }
    }

    public T getObserver() {
        if (observerProxy == null) {
            observerProxy = (T) Proxy.newProxyInstance(callback.getClassLoader(), new Class[]{callback}, this);
        }
        return observerProxy;
    }

    public Map getObservers() {
        return observers;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy