Skip to content

Instantly share code, notes, and snippets.

@dulimarta
Last active January 29, 2016 15:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dulimarta/b2492d10bb95277599d5 to your computer and use it in GitHub Desktop.
Save dulimarta/b2492d10bb95277599d5 to your computer and use it in GitHub Desktop.
DelayedProgressDialog.java
/**
*
*/
package com.appiarium.example;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
/**
* @author Hans Dulimarta
*
* hans.dulimarta@gmail.com, dulimarh@cis.gvsu.edu
*
*/
public class DelayedProgressDialog extends ProgressDialog {
private static Handler dialogHandler;
private Runnable runner;
static {
dialogHandler = new Handler();
}
public DelayedProgressDialog(Context context) {
super(context);
}
public static ProgressDialog show (Context c, CharSequence title, CharSequence msg, long afterDelayMilliSec)
{
final DelayedProgressDialog pd = new DelayedProgressDialog(c);
pd.setTitle(title);
pd.setMessage(msg);
pd.setCancelable(true);
pd.runner = new Runnable() {
public void run() {
try {
pd.show();
}
catch (Exception e) {
/* do nothing */
}
}
};
dialogHandler.postDelayed(pd.runner, afterDelayMilliSec);
return pd;
}
@Override
public void cancel() {
dialogHandler.removeCallbacks(runner);
super.cancel();
}
}
package com.appiarium.example;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
/**
* Created by Hans Dulimarta
* hans.dulimarta@gmail.com, dulimarh@cis.gvsu.edu
*/
public class SampleTask extends AsyncTask<Long,Void,Void> {
private long dialogDelay;
private ProgressDialog progress;
private Context myContext;
public SampleTask(Context c, long d)
{
myContext = c;
dialogDelay = d;
}
@Override
protected void onPreExecute() {
progress = DelayedProgressDialog.show(myContext, "Sample", "Hello", dialogDelay);
// Compare that to the following:
// progress = ProgressDialog.show(myContext, "Sample", "Hello");
}
@Override
protected Void doInBackground(Long... params) {
/* The actual work will replace the following try-catch */
try {
Thread.sleep(params[0]);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
if (progress.isShowing())
progress.dismiss();
progress.cancel(); /* important to invoke cancel() */
Toast.makeText(myContext, "Task completed", Toast.LENGTH_SHORT).show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment