package com.github.jasonhancn.tvcursor.util;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
public class RunsUtils {
private final List<Bean> runnableArrayList = new ArrayList<>();
private final Handler handler = new Handler(Looper.getMainLooper());
private Object result;
private WeakReference<OnRunning> mCallback;
private int currentIndex;
public RunsUtils(Object result) {
this.result = result;
}
public RunsUtils runMainTread(OnRunning runnable) {
runnableArrayList.add(new Bean(1, runnable));
return this;
}
public RunsUtils runOtherTread(OnRunning runnable) {
runnableArrayList.add(new Bean(2, runnable));
return this;
}
public void fire(OnRunning callback) {
if (this.mCallback == null) {
this.mCallback = new WeakReference<>(callback);
}
if (currentIndex < runnableArrayList.size()) {
if (runnableArrayList.get(currentIndex).t == 2) {
new Thread(this::handleCode).start();
} else {
handler.post(this::handleCode);
}
} else {
handler.post(() -> {
if (mCallback.get() != null) mCallback.get().run(result);
clearAll();
});
}
}
private void handleCode() {
if (mCallback == null || mCallback.get() == null) {
clearAll();
return;
}
result = runnableArrayList.get(currentIndex).runnable.run(result);
currentIndex++;
fire(null);
}
private void clearAll() {
for (Bean item : runnableArrayList) {
item.runnable = null;
}
handler.removeCallbacksAndMessages(null);
runnableArrayList.clear();
mCallback.clear();
mCallback = null;
result = null;
}
public static class Bean {
public int t;
public OnRunning runnable;
public Bean(int t, OnRunning runnable) {
this.t = t;
this.runnable = runnable;
}
}
public interface OnRunning {
Object run(Object object);
}
}
使用:
new RunsUtils("I").runMainTread(new RunsUtils.OnRunning() {
@Override
public Object run(Object object) {
return object + " am";
}
}).runOtherTread(new RunsUtils.OnRunning() {
@Override
public Object run(Object object) {
return object + " iron";
}
}).runMainTread(new RunsUtils.OnRunning() {
@Override
public Object run(Object object) {
return object + " man";
}
}).runOtherTread(new RunsUtils.OnRunning() {
@Override
public Object run(Object object) {
return object + " haha";
}
}).fire(new RunsUtils.OnRunning() {
@Override
public Object run(Object object) {
Log.i(TAG, "begin game:" + object);
return object;
}
});
有时候适合自己的才用的舒服