Created
April 24, 2014 16:23
-
-
Save holmeszyx/11260577 to your computer and use it in GitHub Desktop.
自动重试的Runnable, 用于等待UI完成一定程度后触发
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.buy.apps.view; | |
import android.os.Handler; | |
import android.view.View; | |
/** | |
* 自动重试的Runnable, 用于等待UI完成一定程度后触发 | |
* @author holmes | |
* | |
*/ | |
public abstract class AutoTryRunable implements Runnable{ | |
private PostDelegate mDelegate; | |
private boolean mFinished = false; | |
public AutoTryRunable(View v){ | |
mDelegate = new PostDelegate(v); | |
} | |
public AutoTryRunable(Handler handler){ | |
mDelegate = new PostDelegate(handler); | |
} | |
@Override | |
public final void run() { | |
// It is Auto-generated method stub | |
if (!canRun()){ | |
mDelegate.post(this); | |
}else{ | |
doRun(); | |
} | |
} | |
/** | |
* 是否已结束 | |
* @return | |
*/ | |
public boolean isFinished(){ | |
return mFinished; | |
} | |
/** | |
* 停止 | |
*/ | |
public void removeCallback(){ | |
mDelegate.remove(this); | |
} | |
/** | |
* 是否可以执行 | |
* @return | |
*/ | |
public abstract boolean canRun(); | |
/** | |
* 要执行的任务 | |
* @return | |
*/ | |
public abstract void doRun(); | |
/** | |
* Post代理 | |
* @author holmes | |
* | |
*/ | |
private static class PostDelegate{ | |
private final Object mHost; | |
public PostDelegate(View v) { | |
// TODO Auto-generated constructor stub | |
mHost = v; | |
} | |
public PostDelegate(Handler handler){ | |
mHost = handler; | |
} | |
public void post(final Runnable run){ | |
if (mHost instanceof View){ | |
((View) mHost).post(run); | |
}else if (mHost instanceof Handler){ | |
((Handler) mHost).post(run); | |
} | |
} | |
public void remove(Runnable run){ | |
if (mHost instanceof View){ | |
((View) mHost).removeCallbacks(run); | |
}else if (mHost instanceof Handler){ | |
((Handler) mHost).removeCallbacks(run); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment