Skip to content

Instantly share code, notes, and snippets.

@pagetronic
Created January 3, 2023 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pagetronic/2b247d3bc32215df7d438ee2af283084 to your computer and use it in GitHub Desktop.
Save pagetronic/2b247d3bc32215df7d438ee2af283084 to your computer and use it in GitHub Desktop.
/*
* Public Domain @ CPMGN
* Centre de Production Multimédia de la Gendarmerie Nationale
*/
package com.agroneo.grow.system.utils;
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* The type Async task.
*
* @param <Result> the type parameter
*/
public abstract class AsyncTask<Result> {
/**
* The Executor.
*/
private final ExecutorService executor = Executors.newSingleThreadExecutor();
/**
* The Handler.
*/
private final Handler handler = new Handler(Looper.getMainLooper());
/**
* The Is cancelled.
*/
private boolean isCancelled = false;
/**
* Is cancelled boolean.
*
* @return the boolean
*/
public boolean isCancelled() {
return isCancelled;
}
/**
* Cancel.
*/
public final void cancel() {
isCancelled = true;
executor.shutdownNow();
}
/**
* Execute.
*
* @param params the params
*/
public final void execute(Object... params) {
executor.execute(() -> {
Result rez = background(params);
handler.post(() -> executed(rez));
});
}
/**
* Background result.
*
* @param params the params
* @return the result
*/
protected abstract Result background(Object... params);
/**
* Send progress.
*
* @param percent the percent
*/
protected final void sendProgress(int percent) {
handler.post(() -> progress(percent));
}
/**
* Progress.
*
* @param percent the percent
*/
protected void progress(int percent) {
}
/**
* Executed.
*
* @param result the result
*/
protected void executed(Result result) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment