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.0.5
Show newest version
package com.yy.androidlib.util.notification;

import android.os.Handler;
import com.yy.androidlib.util.logging.Logger;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

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

    public Notification(Class callback, Handler handler, Set observers) {
        this.callback = callback;
        this.mainHandler = handler;
        this.observers = observers;
    }

    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) {
        List threadSafe = new ArrayList(observers);
        for (Object observer : threadSafe) {
            if (callback.isInstance(observer)) {
                try {
                    method.invoke(observer, args);
                } catch (Exception e) {
                    Logger.error("notification", "invoke error, method: %s, error: %s", method.getName(), e);
                }
            }
        }
    }

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