public static < E > E onMainThread ( Class < E > callbackInterface , final E callback ) { Utils . notNull ( callbackInterface , "callbackInterface must not be null" ) ; Utils . notNull ( callback , "callback must not be null" ) ; final Handler handler = new Handler ( Looper . getMainLooper ( ) ) ; final String tag = callback . getClass ( ) . getSimpleName ( ) ; Object proxy = Proxy . newProxyInstance ( callbackInterface . getClassLoader ( ) , new Class < ? > [ ] { callbackInterface } , new InvocationHandler ( ) { @ Override public Object invoke ( Object proxy , final Method method , final Object [ ] args ) throws Throwable { handler . post ( new Runnable ( ) { @ Override public void run ( ) { try { method . invoke ( callback , args ) ; } catch ( IllegalAccessException e ) { Log . e ( tag , "Error executing method " + method . getName ( ) + " on main thread." , e ) ; } catch ( IllegalArgumentException e ) { Log . e ( tag , "Error executing method " + method . getName ( ) + " on main thread." , e ) ; } catch ( InvocationTargetException e ) { Log . e ( tag , "Error executing method " + method . getName ( ) + " on main thread." , e ) ; } } } ) ; return null ; } } ) ; return callbackInterface . cast ( proxy ) ; }
Wraps a callback into a proxy that executes its methods on the main thread . Return types are not supported a method with return type other than void always returns null when called on the proxy .