Skip to content

Instantly share code, notes, and snippets.

@holmeszyx
Created April 24, 2014 16:23
Show Gist options
  • Save holmeszyx/11260577 to your computer and use it in GitHub Desktop.
Save holmeszyx/11260577 to your computer and use it in GitHub Desktop.
自动重试的Runnable, 用于等待UI完成一定程度后触发
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