Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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