I implemented an app, inside there's a button to start a CountDownTimer and a TextView to display time left. Someone told me that the timer should run on other thread rather than on main thread, but as I start the timer normally, it 's on the main thread :
_timer = new CountDownTimer(min * 60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
tick();
setChanged();
notifyObservers();
clearChanged();
Log.v("THREAD TIMER : ", "" + Looper.myLooper().getThread().getName());
}
#Override
public void onFinish() {
end = true;
setChanged();
notifyObservers();
clearChanged();
}
};
I use an Observer to update the TextView each time the timer tick, and the code which update the TextView, is also run on the main thread (I confirm it with Looper.myLooper().getThread().getName()). But it didn't affect the TextView at all, but it did print out the debugging that I put to test. Anybody have any idea to fix this ?
Now this is even more confused. I extract the timer part, and formed a new project. Now, it worked. But of course it still didn't work on my actual project :
public class MainActivity extends Activity {
long TIME = 60000;
CountDownTimer _timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button) findViewById(R.id.button_1);
Button b2 = (Button) findViewById(R.id.button_2);
final TextView t1 = (TextView) findViewById(R.id.timer_1);
TextView t2 = (TextView) findViewById(R.id.timer_2);
setUpButton1(b1, t1);
setUpButton2(b2, t2);
}
private void setUpButton2(final Button b2, final TextView t2){
final MyTimer myTimer = new MyTimer();
Observer ob = new Observer() {
#Override
public void update(Observable observable, Object data) {
//t2.setText(myTimer.toString());
t2.post(new Runnable() {
#Override
public void run() {
t2.setText(myTimer.toString());
}
});
Log.v("CLASS TIMER :", Looper.myLooper().getThread().getName() + " thread -- " + myTimer.toString());
}
};
myTimer.addObserver(ob);
b2.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP){
if(b2.isPressed()){
b2.setPressed(false);
myTimer.stopTimer();
}else{
b2.setPressed(true);
myTimer.startTimer();
}
}
return true;
}
});
}
private void setUpButton1(final Button b1, final TextView t1){
b1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP){
if (b1.isPressed() == true){
b1.setPressed(false);
_timer.cancel();
} else {
b1.setPressed(true);
_timer = new CountDownTimer(TIME, 1000) {
#Override
public void onTick(long millisUntilFinished) {
t1.setText("" + millisUntilFinished/1000);
TIME = millisUntilFinished;
}
#Override
public void onFinish() {
}
};
_timer.start();
}
}
return true;
}
});
}
}
Timer class :
public class MyTimer extends Observable{
CountDownTimer myTimer;
long TIME = 60000;
public MyTimer(){
}
public void startTimer(){
myTimer = new CountDownTimer(TIME, 1000) {
#Override
public void onTick(long millisUntilFinished) {
TIME = millisUntilFinished;
setChanged();
notifyObservers();
clearChanged();
}
#Override
public void onFinish() {
}
};
myTimer.start();
}
public void stopTimer(){
myTimer.cancel();
}
public String toString(){
return "" + TIME/1000;
}
}
Anybody have any idea what happened here ? Why it worked in this case, but not work when it's in the whole project ?
Related
I've implemented a CountDownTimer in my code as follows: At the top of the class, I create
CountDownTimer myTimer;
Then when a user presses button Start, the following method is called:
private void countme()
{
final int tick = 500;
final int countTime = 10000;
myTimer = new CountDownTimer(countTime, tick) {
#Override
public void onTick(final long millisUntilFinished) { }
#Override
public void onFinish() {
myPicture.setVisibility(View.GONE);
}
};
myTimer.start();
}
I have button Stop all myTimer.cancel(). As you can see, if the timer is not cancelled, myPicture will disappear.
Even if I click the stop button so that myTimer.cancel() is called (I checked this with log statements), the counter still continues to count down and to make the picture disappear when it's done.
Why isn't it stopping? How do I get it to actually cancel?
To clarify, I do know how to implement Runnable timers, but they are not as accurate for my needs as CountDownTimers are, which is why I'm not using them in this case.
After a lot of tries, trick is to declare the timer in onCreate but start and cancel it in some other method. The onFinish() will not call after cancelling the timer.
myTimer = new CountDownTimer(COUNT_DOWN_TIME, TICK) {
#Override
public void onTick(final long millisUntilFinished) {
((TextView) findViewById(R.id.textView3)).setText(""
+ millisUntilFinished);
}
#Override
public void onFinish() {
findViewById(R.id.timer_imageBiew).setVisibility(View.GONE);
}
};
private fun startTimer() {
myTimer .start()
}
private fun stopTimer() {
myTimer .cancel()
}
Here in your method countme() you are initializing myTimer, so outside this method myTimer has no value.
Use this
Declare at the top
CountDownTimer myTimer;
final int tick = 500;
final int countTime = 10000;
In the onCreate method of Activity or Fragment
myTimer = new CountDownTimer(countTime, tick) {
#Override
public void onTick(final long millisUntilFinished) { }
#Override
public void onFinish() {
myPicture.setVisibility(View.GONE);
}
};
Now use myTimer.start() to start and myTimer.cancel() to stop it.
Hope you understood.
Your post is very odd. I just tried doing a sample activity:
public class MainActivity extends AppCompatActivity {
CountDownTimer myTimer;
Button btnStart;
Button btnCancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample2);
btnStart = (Button) findViewById(R.id.start);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countme();
Toast.makeText(MainActivity.this, "Count Started!", Toast.LENGTH_SHORT).show();
}
});
btnCancel = (Button) findViewById(R.id.cancel_timer);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myTimer.cancel();
Toast.makeText(MainActivity.this, "Clicked Stop Timer!", Toast.LENGTH_SHORT).show();
}
});
}
private void countme() {
final int tick = 500;
final int countTime = 10000;
myTimer = new CountDownTimer(countTime, tick) {
#Override
public void onTick(final long millisUntilFinished) {
Log.d(MainActivity.class.getSimpleName(), "onTick()");
}
#Override
public void onFinish() {
// myPicture.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "In onFinish()", Toast.LENGTH_SHORT).show();
}
};
myTimer.start();
}
}
It works perfectly fine. It stops the timer. But I went and looked around and found this answer where it mentions that CountDownTimer doesn't seem to work, so he suggested to use a Timer instead. Do check it out. Cheers!
This is working example , I have implemented both handler and timer you can pick one .
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class MainActivity extends Activity {
private CountDownTimer myTimer;
final int TICK = 500;
final int COUNT_DOWN_TIME = 2000;
// Option 2 using handler
private Handler myhandler = new Handler();
private Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Option 1 using timer
myTimer = new CountDownTimer(COUNT_DOWN_TIME, TICK) {
#Override
public void onTick(final long millisUntilFinished) {
((TextView) findViewById(R.id.textView3)).setText(""
+ millisUntilFinished);
}
#Override
public void onFinish() {
findViewById(R.id.timer_imageBiew).setVisibility(View.GONE);
}
};
// Option 2 using handler
runnable = new Runnable() {
#Override
public void run() {
findViewById(R.id.handlerImageView).setVisibility(View.GONE);
}
};
findViewById(R.id.start_timer).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
// Option 1 using timer
myTimer.start();
// Option 2 using handler
myhandler.postDelayed(runnable, COUNT_DOWN_TIME);
}
});
findViewById(R.id.stop_timer).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Option 1 stop timer
myTimer.cancel();
// Option 2 stop handler
myhandler.removeCallbacks(runnable);
}
});
}
}
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 want use onTouch in android.
While ACTION_DOWN I want to make button flash in a pattern [ 3 seconds off 3 seconds on ]
I want to do this for 3 intervals of the pattern.
If either ACTION_UP or ACTION_CANCEL is received before the 3 intervals are complete then cancel and leave button visible.
Otherwise call a function.
How would I accomplish this?
I have done similar using vibrator using a pattern.
long pattern[] = new long[] {0, 500, 500, 500, 500, 500, 500, 2000};
vibrator.vibrate(pattern, -1);
Not all devices have vibrator so I wnt to flash button instead.
Any help would be much appreciated.
This code below works but is not very elegant.
There must be a better way.
public class AndroidAnimButtonsActivity extends Activity
{
CountDownTimer countDownTimerOn;
CountDownTimer countDownTimerOff;
CountDownTimer countDownTimerSOS;
ImageButton SOSButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
countDownTimerOn = new CountDownOn(100, 1000);
countDownTimerOff = new CountDownOff(100, 1000);
countDownTimerSOS = new CountDownSOS(3*1000, 1000);
SOSButton = (ImageButton)findViewById(R.id.sosbutton);
SOSButton.setOnTouchListener(new OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN :
SOSButton.setImageResource(R.drawable.panic2);
countDownTimerOff.start();
countDownTimerSOS.start();
break;
case MotionEvent.ACTION_UP :
SOSButton.setImageResource(R.drawable.panic1);
countDownTimerOn.cancel();
countDownTimerOff.cancel();
countDownTimerSOS.cancel();
SOSButton.setVisibility(View.VISIBLE);
break;
case MotionEvent.ACTION_CANCEL :
SOSButton.setImageResource(R.drawable.panic1);
countDownTimerOn.cancel();
countDownTimerOff.cancel();
countDownTimerSOS.cancel();
SOSButton.setVisibility(View.VISIBLE);
break;
}
return false;
}
});
}
public class CountDownOn extends CountDownTimer
{
public CountDownOn(long totalTime, long interval)
{
super(totalTime, interval);
}
#Override
public void onFinish()
{
SOSButton.setVisibility(View.VISIBLE);
countDownTimerOff.start();
}
#Override
public void onTick(long leftTimeInMilliseconds)
{
long seconds = leftTimeInMilliseconds / 1000;
}
}
public class CountDownOff extends CountDownTimer
{
public CountDownOff(long totalTime, long interval)
{
super(totalTime, interval);
}
#Override
public void onFinish()
{
SOSButton.setVisibility(View.INVISIBLE);
countDownTimerOn.start();
}
#Override
public void onTick(long leftTimeInMilliseconds)
{
long seconds = leftTimeInMilliseconds / 1000;
}
}
// CountDownTimer class
public class CountDownSOS extends CountDownTimer
{
public CountDownSOS(long totalTime, long interval)
{
super(totalTime, interval);
}
#Override
public void onFinish()
{
SOSButton.setImageResource(R.drawable.panic2);
SOSButton.setVisibility(View.VISIBLE);
countDownTimerOn.cancel();
countDownTimerOff.cancel();
sendMsg();
}
#Override
public void onTick(long leftTimeInMilliseconds)
{
long seconds = leftTimeInMilliseconds / 1000;
}
}
public void sendMsg()
{
Toast.makeText(getApplicationContext(),"SOS", Toast.LENGTH_SHORT).show();
}
}
I want to do app to show 3 elements (each 2 seconds) and each start showing after the before element. Here is code:
public class Remember extends Activity
{
TextView text;
ImageView element1, element2, element3, element4 ,element5, element6;
Button button1, button2, button3, button4, button5, button6;
int data, id;
Random random;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remember);
random = new Random();
id=1;
text = (TextView)findViewById(R.id.text);
element1 = (ImageView)findViewById(R.id.element1);
element2 = (ImageView)findViewById(R.id.element2);
element3 = (ImageView)findViewById(R.id.element3);
element4 = (ImageView)findViewById(R.id.element4);
element5 = (ImageView)findViewById(R.id.element5);
element6 = (ImageView)findViewById(R.id.element6);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
button5 = (Button) findViewById(R.id.button5);
button6 = (Button) findViewById(R.id.button6);
element1.setVisibility(View.GONE);
element2.setVisibility(View.GONE);
element3.setVisibility(View.GONE);
element4.setVisibility(View.GONE);
element5.setVisibility(View.GONE);
element6.setVisibility(View.GONE);
data = random.nextInt(6)+1;
}
public void button1(View v)
{
gameStart();
}
public void gameStart()
{
do{
if (data==1)
{
CountDownTimer cdt = new CountDownTimer(2000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
element1.setVisibility(View.VISIBLE);
}
#Override
public void onFinish()
{
element1.setVisibility(View.GONE);
}
}.start();
}
else if (data==2)
{
CountDownTimer cdt = new CountDownTimer(2000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
element2.setVisibility(View.VISIBLE);
}
#Override
public void onFinish()
{
element2.setVisibility(View.GONE);
}
}.start();
}
else if (data==3)
{
CountDownTimer cdt = new CountDownTimer(2000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
element3.setVisibility(View.VISIBLE);
}
#Override
public void onFinish()
{
element3.setVisibility(View.GONE);
}
}.start();
}
else if (data==4)
{
CountDownTimer cdt = new CountDownTimer(2000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
element4.setVisibility(View.VISIBLE);
}
#Override
public void onFinish()
{
element4.setVisibility(View.GONE);
}
}.start();
}
else if (data==5)
{
CountDownTimer cdt = new CountDownTimer(2000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
element5.setVisibility(View.VISIBLE);
}
#Override
public void onFinish()
{
element5.setVisibility(View.GONE);
}
}.start();
}
else if (data==6)
{
CountDownTimer cdt = new CountDownTimer(2000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
element6.setVisibility(View.VISIBLE);
}
#Override
public void onFinish()
{
element6.setVisibility(View.GONE);
}
}.start();
}
id=id+1;
text.setText("cos " + id);
data = random.nextInt(6)+1;
try
{
Thread.sleep(2000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}while(id<=3);
}
}
But if I clicked start application start lagging and everything go to norm after time which all elements should be hide. If I delete Thread.sleep all elements show in the same time. What should I do?
Thread.sleep(2000); on the ui thread blocks the ui thread. You should never block the ui thread. Remove the sleep.
To create a delay use a Handler.
Read
http://developer.android.com/guide/components/processes-and-threads.html
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();
}