Last active
June 14, 2022 06:48
-
-
Save yava555/ad3d610856973239fae76f01aedc3510 to your computer and use it in GitHub Desktop.
BackGroundTask 后台任务
This file contains 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
public class APIException extends RuntimeException { | |
private int code; | |
private String msg; | |
public APIException(int code, String msg) { | |
this.code = code; | |
this.msg = msg; | |
} | |
public APIException(String msg) { | |
this.msg = msg; | |
} | |
public int getCode() { | |
return code; | |
} | |
public String getMsg() { | |
return msg; | |
} | |
} |
This file contains 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
public interface BgTask<T> { | |
T execute() throws Exception; | |
} |
This file contains 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
public class BgTaskExecutor { | |
public static Executor executor = Executors.newFixedThreadPool(5); | |
public static <T> void execute(BgTask<T> bgTask, BgTaskCallback<T> callback) { | |
executor.execute(() -> { | |
try { | |
T result = bgTask.execute(); | |
callback.respData(result); | |
} catch (APIException apiException) { | |
callback.respFail(apiException.getCode(), apiException.getMsg()); | |
} catch (Throwable e) { | |
callback.respFail(-1, "接口异常,请稍后再试"); | |
} | |
}); | |
} | |
public static abstract class BgTaskCallback<T> { | |
private final Handler handler = new Handler(Looper.getMainLooper()); | |
private void runMain(Runnable r) { | |
handler.post(r); | |
} | |
public void respData(T data) { | |
runMain(() -> onData(data)); | |
} | |
public void respFail(String message) { | |
respFail(-1, message); | |
} | |
public void respFail(int code, String message) { | |
runMain(() -> { | |
onFail(code, message); | |
return; | |
}); | |
} | |
protected abstract void onData(T data); | |
protected abstract void onFail(int code, String message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment