Skip to content

Instantly share code, notes, and snippets.

@ericwoodruff
Last active December 22, 2015 02:18
Show Gist options
  • Save ericwoodruff/6401954 to your computer and use it in GitHub Desktop.
Save ericwoodruff/6401954 to your computer and use it in GitHub Desktop.
Android progress/status long duration toast with catchable async task loader
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.CountDownTimer;
import android.widget.Toast;
@SuppressLint({ "ViewConstructor", "ShowToast" })
public class ProgressToast {
public ProgressToast (Activity context, String text) {
this.context = context;
this.text = text;
}
public void show () {
if (null != this.timer) {
this.timer.cancel ();
}
context.runOnUiThread (new Runnable () {
@Override
public void run () {
toast = Toast.makeText (context, text, Toast.LENGTH_LONG);
timer = new CountDownTimer (30000, 1000) { // 30 seconds max
@Override
public void onTick (long millisUntilFinished) {
toast.show ();
}
@Override
public void onFinish () {
toast.cancel ();
}
};
toast.show ();
timer.start ();
}
});
}
public void cancel () {
context.runOnUiThread (new Runnable () {
@Override
public void run () {
if (null != timer) {
timer.cancel ();
timer = null;
}
toast.cancel ();
}
});
}
public void setText (final String text) {
context.runOnUiThread (new Runnable () {
@Override
public void run () {
toast.setText (text);
}
});
}
private Activity context;
private Toast toast;
private String text;
private CountDownTimer timer;
}
import android.app.Activity;
public abstract class ToastProgressCatchableAsyncTaskLoader<D, T extends Throwable> extends CatchableAsyncTaskLoader<D, T> {
public ToastProgressCatchableAsyncTaskLoader (Activity context, String loadingText) {
super (context);
this.activity = context;
this.toast = new ProgressToast (activity, loadingText);
}
@Override
public Catchable<D, T> loadInBackground () {
try
{
toast.show ();
return super.loadInBackground ();
} finally {
toast.cancel ();
}
}
public void setToastText (String text) {
toast.setText (text);
}
private Activity activity;
private ProgressToast toast;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment