public abstract class iCmd {
private boolean mCanceled = false;
private Object mTag;
public void cancel() {
mCanceled = true;
}
public boolean isCanceled() {
return mCanceled;
}
public Object getTag() {
return mTag;
}
public iCmd setTag(Object tag) {
mTag = tag;
return this;
}
public abstract Bundle exe() throws Exception;
}
public interface iCmdListener {
public void onPreExecute();
// public void onProgressUpdate(int progress);
public void onPostExecute(Bundle resultBundle);
}
public class iCmdExecutor {
//用于取消和具体tag相关的cmd
public static void cancelAll(final Object tag)
//异步执行该命令,并在主线程执行回调通知
public static void exeAsync(final iCmd cmd, final iCmdListener listener,
Object tag)
//同步执行该命令,并在当前线程执行回调通知
public static void exeSync(iCmd cmd, iCmdListener listener, Object tag)
}
public class CmdAdd extends iCmd {
private static final String TAG = "test";
private BigInteger a;
private BigInteger b;
public CmdAdd(BigInteger a, BigInteger b) {
this.a = a;
this.b = b;
}
@Override
public Bundle exe() throws InterruptedException {
Log.i(TAG, this + ", exe, tid=" + Thread.currentThread().getId());
Thread.sleep(5000);// demo for long operation
Bundle bundle = new Bundle();
bundle.putString("result", a.add(b).toString());
return bundle;
}
}
iCmdExecutor.exeAsync(new CmdAdd(new BigInteger("123"), new BigInteger(
"12345678901234567890123456789012345678901234567890")),
new iCmdListener() {
@Override
public void onPreExecute() {
Log.e(TAG, "onPreExecute, tid="
+ Thread.currentThread().getId());
}
@Override
public void onPostExecute(Bundle resultBundle) {
Log.e(TAG, "onPostExecute, tid="
+ Thread.currentThread().getId()
+ ", resultBundle=" + resultBundle);
if (null != resultBundle) {
String res = resultBundle.getString("result");
tvAddResult.setText(res);
}
}
}, this);
iCmdExecutor.cancelAll(this);
原文地址:http://blog.csdn.net/cheyiliu/article/details/45689181