how can I put a Timer in an android dialog? I have all the dialog methods built, but I can't seem to figure out how to update the text in the dialog view every time the timer fires. my update method is already getting called once per second by another class.
here's my code so far:
public class PlaybackTimerEndingDialog extends DialogFragment implements TimerCallbacks.updateTimer {
private AlertDialog.Builder mBuilder;
private long mTime;
private Context mContext;
private View mTimerEndingView;
public PlaybackTimerEndingDialog(long startTime, Context context){
this.mTime = startTime;
this.mContext = context;
}
private void updateView(String message_text){
LayoutInflater inflater = this.getActivity().getLayoutInflater();
this.mTimerEndingView = inflater.inflate(R.layout.playback_timer_ending, null);
TextView messageView = (TextView) this.mTimerEndingView.findViewById(R.id.timer_ending_message);
messageView.setText(message_text);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
this.updateView("The sleep timer will expie in "+ this.formatTime(this.mTime));
this.mBuilder = new AlertDialog.Builder(this.mContext)
// this.mBuilder.setMessage("The sleep timer will expie in "+ this.formatTime(this.mTime))
.setPositiveButton("Add more time", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
TimerCallbacks.createTimer listener = (TimerCallbacks.createTimer) PlaybackTimerEndingDialog.this.mContext;
listener.createTimerDialog();
}
})
.setNegativeButton("Cancel timer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
TimerCallbacks.createTimer listener = (TimerCallbacks.createTimer) PlaybackTimerEndingDialog.this.mContext;
listener.stopTimer();
}
});
this.mBuilder.setView(this.mTimerEndingView);
// Create the AlertDialog object and return it
return this.mBuilder.create();
}
#Override
public void finished() {
// TODO Auto-generated method stub
}
#Override
public void update(long time) {
// TODO Auto-generated method stub
// this.getDialog().set
this.updateView("The sleep timer will expie in "+ this.formatTime(time));
this.mTime = time;
Log.d("current time", Long.toString(time));
// this.mBuilder.setMessage("The sleep timer will expie in "+ this.formatTime(time));
}
private String formatTime(long time) {
int seconds = (int) (time / 1000) % 60 ;
int minutes = (int) ((time / (1000*60)) % 60);
String mnStr = (minutes<10 ? "0" : "")+minutes;
String secStr = (seconds<10 ? "0" : "")+seconds;
return "-"+mnStr +":"+ secStr;
}
}
any help with this would be greatly appreciated.
Put that in some function where you want to start a timer.
final Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
updateView("fired");
}
}, 1000);
Update: it's the update method that inflate new layout every time, while the dialog is using first inflated layout.
Related
I have a CountDownTimer that dismisses a dialog popup window. I would like for this timer to restart if the user touches the screen. Here is what I have so far,
public class dataCapture extends Fragment implements OnClickListener {
...
MotionEvent event;
View.OnTouchListener touchListener;
#Override
public void onCreate(Bundle savedDataEntryInstanceState) {
super.onCreate(savedDataEntryInstanceState);
setRetainInstance(true);
}
...
#Override
public View onCreateView
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnHelpFilexml:
openHelpDialog();
break;
...
}
private void openHelpDialog() {
Button btnCloseWindow;
final Dialog helpDialog;
TextView tvHelpDialogTitle, tvHelpDialogBody;
helpDialog = new Dialog(getActivity(), android.R.style.Theme_Translucent);
helpDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
helpDialog.setCancelable(true);
helpDialog.setContentView(R.layout.help_dialog);
tvHelpDialogTitle = (TextView) helpDialog.findViewById(R.id.tvHelpDialogTitle);
tvHelpDialogTitle.setText("DataCapture Help");
tvHelpDialogBody = (TextView) helpDialog.findViewById(R.id.tvHelpDialogBody);
tvHelpDialogBody.setText("Start of help text\n" +
"This is help text\n" +
"\n" +
"Here we go...\n" +
...
"This is the end.");
btnCloseWindow = (Button) helpDialog.findViewById(R.id.btnCloseWindow);
btnCloseWindow.setText("Close");
btnCloseWindow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
helpDialog.dismiss();
}
});
CountDownTimer countDownTimer = new CountDownTimer(30000, 1000) {
// new countDownTimer(30000, 1000) {//makes popup go away after 30 secs
#Override
public void onTick(long millisUntilFinished) {//Do something every second...
}
#Override
public void onFinish() {//action at end of specified time
helpDialog.dismiss();
}
}.start();
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_DOWN) {
countDownTimer.cancel();
countDownTimer.start();
}
return super.onTouchEvent(event);
}
helpDialog.show();
}
}
Any suggestions regarding how best to implement this function would be highly appreciated. Copious TIA.
UPDATE Got it. Solution below. Thanks.
public class dataCapture extends Fragment implements OnClickListener {
...
private static final int COUNTDOWN_TIME_MS = 30000;
Handler handlerHelpDialogTimer;
Runnable runnableHelpDialogDismissCountdown;
Dialog helpDialog;
private Dialog getHelpDialog() {
Button btnCloseWindow;
final Dialog helpDialog;
TextView tvHelpDialogTitle, tvHelpDialogBody;
helpDialog = new Dialog(getActivity(), android.R.style.Theme_Translucent);
helpDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
helpDialog.setCancelable(true);
helpDialog.setContentView(R.layout.help_dialog);
tvHelpDialogTitle = (TextView) helpDialog.findViewById(R.id.tvHelpDialogTitle);
tvHelpDialogTitle.setText("DataCapture Help");
tvHelpDialogBody.setText("Start of help text\n" +
"This is help text\n" +
"\n" +
"Wheee, here we go\n" +
...
"this is the end.");
btnCloseWindow = (Button) helpDialog.findViewById(R.id.btnCloseWindow);
btnCloseWindow.setText("Close");
btnCloseWindow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
helpDialog.dismiss();
}
});
tvHelpDialogBody.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View tvHelpDialogBody, MotionEvent event) {
cancelCountdown();
startCountdown();
return false;
}
});
helpDialog.show();
return (helpDialog);
}
private void showHelpDialog() {
helpDialog = getHelpDialog();
helpDialog.show();
startCountdown();
}
synchronized private void startCountdown() {
handlerHelpDialogTimer.postDelayed(getCountdownTask(), COUNTDOWN_TIME_MS);
}
synchronized private void cancelCountdown() {
handlerHelpDialogTimer.removeCallbacks(runnableHelpDialogDismissCountdown);
runnableHelpDialogDismissCountdown = null;
}
private Runnable getCountdownTask() {
Runnable task = new Runnable() {
#Override
public void run() {
if (helpDialog != null) helpDialog.dismiss();
}
};
runnableHelpDialogDismissCountdown = task;
return task;
}
Ditch the countdown timer. Instead use a handler, for example:
public class AwesomeActivity extends Activity {
private static final int COUNTDOWN_TIME_MS = 300000;
Handler handler;
Runnable countDown;
Dialog helpDialog;
#Override public void onCreate(Bundle b) {
super.onCreate(b);
handler = new Handler();
}
/* call cancelCountdown() in onPause* */
private Dialog getHelpDialog() { return /* fill in the details */ }
private void showHelpDialog() {
helpDialog = getHelpDialog();
helpDialog.show();
startCountDown();
}
synchronized private void startCountDown() {
handler.postDelayed(getCountdownTask(), COUNTDOWN_TIME_MS);
}
synchronized private void cancelCountdown() {
handler.removeCallbacks(countdown);
countdown = null;
}
private Runnable getCountdownTask() {
Runnable task = new Runnable() {
#Override public void run() {
if (helpDialog != null) helpDialog.dismiss();
}
};
countDown = task;
return task;
}
}
Now in onTouch(MotionEvent e) you can cancel and start the countdown.
I'll leave it to you to figure out how to handle onPause and onResume :)
Furthermore, if you really wanted to, you could override a Dialog and put the Handler timer countdown logic inside that class, overriding show() to start the countdown and then add a method such as, restartTimer() you can call after a TOUCH_DOWN. If you do, you can then also override onSaveInstanceState and onRestoreInstanceState in the Dialog subclass, to cancel the callback, stash the time remaining, then pull out the time remaining and re-postdelay the countdown runnable with the remaining time.
I have an application in which when the user starts the application a timer starts. After 10sec an AlertDialog pops up saying only 15 seconds reaming and displays a timer, and after 14 seconds it disappears. This works fine when on the first activity of the application. If the user passes from first Activty --> TimedNotify Activity the timer stops after 10seconds. onUserInteraction() in TimedNotify the timer restarts and works absolutely fine. Please assist me as to where I am going wrong.
public class FirstActivity extends TimedNotify{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.timercheck);
final Button btnstart2 = (Button) findViewById(R.id.btn);
btnstart2.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(FirstActivity.this,
TimedNotify.class);
startActivity(intent);
}
});
}
}
public class TimedAlert extends Activity
{
static CountDownTimer timer1, timer2;
int flag = 0;
protected static final String TAG = null;
public static AlertDialog alert, alertdialog;
private static Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView mCounter1TextField = (TextView) findViewById (R.id.mCounter1TextField);
// first timer set for 10sec
timer1 = new CountDownTimer(10000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
Log.v(TAG, "timer1 ticking");
mCounter1TextField.setText("Seconds left: "
+ formatTime(millisUntilFinished));
}
public void onFinish() {
//after 10sec display alert box and show timer
Log.v(TAG, "timer1 finished");
timer1.cancel();
AlertDialog.Builder builder = new AlertDialog.Builder(
TimedAlert.this);
builder.setTitle("Session Time Out");
builder.setMessage("00:15");
builder.setPositiveButton("Resume", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog2,int iwhich)
{
Intent in = new Intent(TimedAlert.this,FirstActivity.class);
//in case there are many events ..the intent should be passed to the last activity on clicking resume
in.setAction(Intent.ACTION_MAIN);
in.addCategory(Intent.CATEGORY_LAUNCHER);
onUserInteraction();
}
});
builder.setNegativeButton ("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog2,int iwhich)
{
timer2.cancel();
timer1.start();
}
});
alert = builder.create();
alert.show();
timer2 = new CountDownTimer(15000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
Log.v(TAG, "timer2 ticking");
alert.setMessage("Your Session will expire in 5 minutes . Timleft00:"+ (millisUntilFinished / 1000));
mCounter1TextField.setText("Seconds left: "+ formatTime (millisUntilFinished));
}
//after 15 sec dismiss alert box
public void onFinish() {
Log.v(TAG, "timer2 finished");
timer2.cancel();
alert.dismiss();
}
}.start();
}
}.start();
}
#Override
public void onBackPressed() {
Intent in = new Intent(TimedAlert.this, FirstActivity.class);
startActivity(in);
}
public String formatTime(long millis) {
String output = "00:00";
long seconds = millis / 1000;
long minutes = seconds / 60;
seconds = seconds % 60;
minutes = minutes % 60;
String secondsD = String.valueOf(seconds);
String minutesD = String.valueOf(minutes);
if (seconds < 10)
secondsD = "0" + seconds;
if (minutes < 10)
minutesD = "0" + minutes;
output = minutesD + " : " + secondsD;
return output;
}
public void onUserInteraction() {
super.onUserInteraction();
// Remove any previous callback
try {
Log.v(TAG, "user interacted");
timer1.start();
timer2.cancel();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.v(TAG, "paused");
onUserInteraction();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.v(TAG, "resumed");
onUserInteraction();
}
private void handleIntent(Intent intent) {
timer1.start();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.v(TAG, "stopped");
timer1.start();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.v(TAG, "started");
timer1.start();
}
}
OK, here are a few things I noted that might help you out:
public void onClick(DialogInterface dialog2, int iwhich) {
Intent in = new Intent(TimedAlert.this,
FirstActivity.class);
in.setAction(Intent.ACTION_MAIN);
in.addCategory(Intent.CATEGORY_LAUNCHER);
onUserInteraction();
}
You don't have a startActivity(in); after setting up all the parameters.
Why do onPause() and onResume() call onUserInteraction(), but onStart() and onStop() don't?
In fact, you should choose whether to use onPause() and onResume() only or onStart() and onStop(). Furthermore, onPause() or onStop() shouldn't restart the timers?
Thinking further about your reported problem, you say that it is when you are on your second activity that you have problems. Check out the lifecycle of an Activity - I suspect what might be happening is that you launch a new instance of your activity. Try setting your manifest to use android:launch mode="singleTask" for your activity.
I want to do countdown timer with pause and restart.Now i am displaying countdown timer By implenting ontick() and onfinish().please help me out.HEre is th code for countdown timer
final CountDownTimer Counter1 = new CountDownTimer(timervalue1 , 1000)
{
public void onTick(long millisUntilFinished)
{
System.out.println("onTick method!"(String.valueOf(millisUntilFinished/1000)));long s1=millisUntilFinished;
}
public void onFinish()
{
System.out.println("Finished!");
}
}
in onTick method..save the milliseconds left
long s1=millisUntilFinished;
when you want to pause the timer use..
Counter.cancel();
when you want to resume create a new countdowntimer with left milliseconds..
timervalue=s1
counter= new Counter1();
counter.start();
See this link
I would add something to the onTick handler to save the progress of the timer in your class (number of milliseconds left).
In the onPause() method for the activity call cancel() on the timer.
In the onResume() method for the activity create a new timer with the saved number of milliseconds left.
Refer the below links
LINK
LINK
My first answer on stackOverFlow, hope it should help :) ...
This is how I solved the problem, control timer from Fragment, Bottomsheet, Service, Dialog as per your requirement, keep a static boolean variable to control.
declare in your Activity:
long presetTime, runningTime;
Handler mHandler =new Handler();
Runnable countDownRunnable;
Toast toastObj;
public static boolean shouldTimerRun = true;
TextView counterTv;
In onCreate:
presetTime =60000L;
runningTime= presetTime;
//setting up Timer
countDownRunnable=new Runnable() {
#Override
public void run() {
if (shouldTimerRun) //if false, it runs but skips counting
{
counterTv.setText(simplifyTimeInMillis(runningTime));
if (runningTime==0) {
deployToast("Task Completed"); //show toast on task completion
}
runningTime -= 1000;
presetTime = runningTime; //to resume the timer from last position
}
mHandler.postDelayed(countDownRunnable,1000); //simulating on-tick
}
};
mHandler.post(countDownRunnable); // Start our CountdownTimer
Now, whenever you want to pause the timer change the value of shouldTimerRun false and to resume make it true.
#Override
public void onResume() {
super.onResume();
shouldTimerRun=true;
}
#Override
public void onPause() {
super.onPause();
shouldTimerRun=false;
deployToast("Timer is paused !!");
}
Helping methods: (can be skipped)
public static String simplifyTimeInMillis(long time) {
String result="";
long difference = time;
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
if (difference<1000){
return "0";
}
if (difference>=3600000) {
result = result + String.valueOf(difference / hoursInMilli) + "hr ";
difference = difference % hoursInMilli;
}
if (difference>=60000) {
result = result + String.valueOf(difference / minutesInMilli) + "m ";
difference = difference % minutesInMilli;
}
if (difference>=1000){
result = result + String.valueOf(difference / secondsInMilli) + "s";
}
return result;
}
public void deployToast(String msg){
if (toastObj!=null)
toastObj.cancel();
toastObj = Toast.makeText(mContext,msg,Toast.LENGTH_SHORT);
toastObj.show();
}
I'm using two private vars in this case:
private long startPauseTime;
private long pauseTime = 0L;
public void pause() {
startPauseTime = System.currentTimeMillis();
}
public void resumen(){
pauseTime += System.currentTimeMillis() - startPauseTime;
}
I am afraid that it is not possible to pause or stop CountDownTimer and pausing or stopping in onTick has no effect whatsoever user TimerTask instead.
Set up the TimerTask
class UpdateTimeTask extends TimerTask {
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timeLabel.setText(String.format("%d:%02d", minutes, seconds));
}
}
if(startTime == 0L) {
startTime = evt.getWhen();
timer = new Timer();
timer.schedule(new UpdateTimeTask(), 100, 200);
}
You can add event listener's like this..
private Handler mHandler = new Handler();
...
OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v) {
if (mStartTime == 0L) {
mStartTime = System.currentTimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
}
}
};
OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
mHandler.removeCallbacks(mUpdateTimeTask);
}
};
For more refer to Android Documentation.
//This timer will show min:sec format and can be paused and resumed
public class YourClass extends Activity{
TextView timer;
CountDownTimer ct;
long c = 150000; // 2min:30sec Timer
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.YourXmlLayout);
timer = (TextView)findViewById(R.id.Yourtimer)
startTimer(); // it will start the timer
}
public void startTimer(){
ct = new CountDownTimer(c,1000) {
#Override
public void onTick(long millisUntilFinished) {
// Code to show the timer in min:sec form
// Here timer is a TextView so
timer.setText(""+String.format("%02d:%02d",millisUntilFinished/60000,(millisUntilFinished/1000)%60));
c = millisUntilFinished; // it will store millisLeft
}
#Override
public void onFinish() {
//your code here
}
};
ct.start();
}
/*===========================================================
*after creating this you can pause this by typing ct.cancel()
*and resume by typing startTimer()*/
public class MainActivity extends AppCompatActivity {
TextView textView;
CountDownTimer ctimer;
boolean runCountDown;
private long leftTime;
private static final long MILL_IN_FUTURE = 6000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view);
textView.setText("Click to start");
textView.setOnClickListener(this::clickStartAndPauseAndResume);
leftTime = MILL_IN_FUTURE;
}
public void clickStartAndPauseAndResume(View view) {
if (!runCountDown) {
long time = (leftTime == 0 || leftTime == MILL_IN_FUTURE) ? MILL_IN_FUTURE : leftTime;
ctimer = new CountDownTimer(time, 1) {
#Override
public void onTick(long l) {
leftTime = l;
textView.setText(l + "ms");
}
#Override
public void onFinish() {
textView.setText("Done");
leftTime = 0;
runCountDown = false;
textView.postDelayed(new Runnable() {
#Override
public void run() {
textView.setText("Click to start");
}
}, 1000);
}
}.start();
runCountDown = true;
} else {
ctimer.cancel();
textView.setText(textView.getText() + "\n Click to resume");
runCountDown = false;
}
}
}
A nice and simple way to create a Pause/Resume for your CountDownTimer is to create a separate method for your timer start, pause and resume as follows:
public void timerStart(long timeLengthMilli) {
timer = new CountDownTimer(timeLengthMilli, 1000) {
#Override
public void onTick(long milliTillFinish) {
milliLeft=milliTillFinish;
min = (milliTillFinish/(1000*60));
sec = ((milliTillFinish/1000)-min*60);
clock.setText(Long.toString(min)+":"+Long.toString(sec));
Log.i("Tick", "Tock");
}
The timerStart has a long parameter as it will be reused by the resume() method below. Remember to store your milliTillFinished (above as milliLeft) so that you may send it through in your resume() method. Pause and resume methods below respectively:
public void timerPause() {
timer.cancel();
}
private void timerResume() {
Log.i("min", Long.toString(min));
Log.i("Sec", Long.toString(sec));
timerStart(milliLeft);
}
Here is the code for the button FYI:
startPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(startPause.getText().equals("Start")){
Log.i("Started", startPause.getText().toString());
startPause.setText("Pause");
timerStart(15*1000);
} else if (startPause.getText().equals("Pause")){
Log.i("Paused", startPause.getText().toString());
startPause.setText("Resume");
timerPause();
} else if (startPause.getText().equals("Resume")){
startPause.setText("Pause");
timerResume();
}
My Problem is I am Running one Method into Thread and after 30 Seconds I will display alertdialog and click on alertdialog's ok button i will stop current thread but problem is thread is not stop, following is my Code and sorry for bad english comunication
public class CountDownTimerActivity extends Activity implements Runnable {
Thread t;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = new Thread(this);
t.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
myTimer.start();
mDeclaration();
myTimer.cancel();
}
private CountDownTimer myTimer = new CountDownTimer(30000, 1000) {
// This will give you 30 sec timer with each tick at 1 second
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
t.interrupt();
//t.stop();
AlertDialog.Builder alert = new AlertDialog.Builder(
CountDownTimerActivity.this);
alert.setMessage("Loading...");
alert.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.show();
}
};
public void mDeclaration() {
for (int i = 0; i < 100000; i++) {
System.out.println("Printing OK" + i);
}
}
}
see this question...instead you can put a flag in run method.. and check whether to run or not to run the code in thread.
try this:-
public class CountDownTimerActivity extends Activity implements Runnable {
Thread t;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = new Thread(this);
t.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
myTimer.start();
mDeclaration();
myTimer.cancel();
}
private CountDownTimer myTimer = new CountDownTimer(30000, 1000) {
// This will give you 30 sec timer with each tick at 1 second
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
AlertDialog.Builder alert = new AlertDialog.Builder(
CountDownTimerActivity.this);
alert.setMessage("Loading...");
alert.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// t.interrupt();
t.stop();
}
});
alert.show();
}
};
public void mDeclaration() {
for (int i = 0; i < 100000; i++) {
System.out.println("Printing OK" + i);
}
}
}
I want to set timeout for Dialog (progress dialog) in android , to make the dialog disappears after a period of time (if there is No response for some action !)
The same approach as in this post is verified to work (with long instead of float):
public void timerDelayRemoveDialog(long time, final Dialog d){
new Handler().postDelayed(new Runnable() {
public void run() {
d.dismiss();
}
}, time);
}
You could always make a class called ProgressDialogWithTimeout and override the functionality of the show method to return a ProgressDialog and set a timer to do what you wish when that timer goes off. Example:
private static Timer mTimer = new Timer();
private static ProgressDialog dialog;
public ProgressDialogWithTimeout(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public ProgressDialogWithTimeout(Context context, int theme) {
super(context, theme);
// TODO Auto-generated constructor stub
}
public static ProgressDialog show (Context context, CharSequence title, CharSequence message)
{
MyTask task = new MyTask();
// Run task after 10 seconds
mTimer.schedule(task, 0, 10000);
dialog = ProgressDialog.show(context, title, message);
return dialog;
}
static class MyTask extends TimerTask {
public void run() {
// Do what you wish here with the dialog
if (dialog != null)
{
dialog.cancel();
}
}
}
Then you would call this in your code as so:
ProgressDialog progressDialog = ProgressDialogWithTimeout.show(this, "", "Loading...");