You can use AsyncTask for this purpose, however, it has been deprecated in Sdk 30 and recommended to use the java.concurrent.* utilities directly docs. Following is an workaround using ExecutorService, although it is not perfect, it definitely meets your functionality:
In your Activity (say, MyActivity), create a member of ExecutorService and initialize it. Add method and callback like following, when you want to perform some background task, just call it:
public class MyActivity extends AppCompatActivity {
// You can use your preferred executor
private final ExecutorService executor = new ThreadPoolExecutor(0, 1,
3L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>());
@Override
protected void onCreate (Bundle savedInstanceState) {
// Initiate the task
executeParallel(new Callable<Boolean> {
@Override
public Boolean call() {
// Perform your task and return boolean
return trueOrFalse;
}
}, new Callback<Boolean>() {
@Override
public void onStart() {
// Show progress dialog
progressDialog.show();
}
@Override
public void onComplete(Boolean result) {
if (result) {
// Do some tasks
} else {
// Do other tasks
}
// Remove dialog
progressDialog.dismiss();
}
}, new Handler(Looper.getMainLooper()));
}
public <R> void executeParallel(@NonNull Callable<R> callable, @Nullable Callback<R> callback, Handler handler) {
executor.execute(() -> {
handler.post(() -> {
if (callback != null) {
callback.onStart();
}
});
R r = null;
try {
r = callable.call();
} catch (Exception e) {
// Ignore
} finally {
R result = r;
handler.post(() -> {
if (callback != null) {
callback.onComplete(result);
}
});
}
});
}
public interface Callback<R> {
void onStart();
void onComplete(R result);
}
}
When you are done, just shut down the ExecutorService. This Executor and related methods can be moved into ViewModel if you use them for better design. Remember, you should not use Thread directly to avoid potential memory leak.