CountDownTimer with Seekbar - android

Hi I have implemented CountDownTimer timer with SeekBar and it is working fine, my problem is i am not able to change the timer when i drag the seek bar how to achieve this.
Example: If i drag and increase the CountDownTimer it should increase the time like that decrease also.
CountDownTimer Code:
private void startTimer(final int minuti) {
countDownTimer = new CountDownTimer(60 * minuti * 1000 ,
500) {
// 500 means, onTick function will be called at every 500
// milliseconds
#Override
public void onTick(long leftTimeInMilliseconds) {
circularSeekbar.setMax(60 * minuti);
int barVal = 0;
barVal = ((int) (minuti * 60 ) - (int) (seconds));
circularSeekbar.setProgress(-barVal);
mTvTime.setText(String.format("%02d", seconds / 60) + ":"
+ String.format("%02d", seconds % 60));
Log.d("TIME", mTvTime.getText().toString());
}
#Override
public void onFinish() {
}
}.start();
}
Seekbar code:
public class CircleSeekBarListener implements
OnCircularSeekBarChangeListener {
#Override
public void onProgressChanged(CircularSeekBar circularSeekBar,
int progress, boolean fromUser) {
if (fromUser) {
}
}
#Override
public void onStopTrackingTouch(CircularSeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(CircularSeekBar seekBar) {
// TODO Auto-generated method stub
}
}

here is code
set your seekbar in onTick
timer = new CounterClass(150000, 1000);
timer.start();
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
// timeTextView.setText("Completed.");
this.cancel();
AppUtills.FROMTIME_FINISH = true;
finish();
}
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
caaryLong = millis;
String hms = String.format(
"%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
System.out.println(hms);
timeTextView.setText(hms);
}
}

Try this code.
public class MainActivity extends AppCompatActivity {
private int seconds = 120; // two min
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
circularSeekbar = (SeekBar) findViewById(R.id.circularSeekbar);
mTvTime = (TextView) findViewById(R.id.mTvTime);
circularSeekbar.setMax(seconds);
circularSeekbar.setProgress(seconds);
circularSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(fromUser) {
seconds = progress;
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
startTimer(seconds * 1000);
}
});
startTimer(seconds * 1000);
}
private void startTimer(final long milisecods) {
if (countDownTimer != null) {
countDownTimer.cancel();
}
countDownTimer = new CountDownTimer(milisecods, 500) {
// 500 means, onTick function will be called at every 500
// milliseconds
#Override
public void onTick(long leftTimeInMilliseconds) {
int barVal = (int) leftTimeInMilliseconds / 1000;
circularSeekbar.setProgress(barVal);
mTvTime.setText(String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(leftTimeInMilliseconds),
TimeUnit.MILLISECONDS.toSeconds(leftTimeInMilliseconds) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(leftTimeInMilliseconds))
));
}
#Override
public void onFinish() {
}
}.start();
}
}

Related

countdowntimer with sound.is it possible?

I want to ask a question I have put the timer to count down from 10:00 min..I want it when it goes at 2 min to put a sound for 10 seconds like an error sound or alarm sound is that possible and if it is can I have some help plz??
Yes it's possible, all you have to do to check the remaining time and play the sound accordingly:
private static final int Two_Seconds = 120000;
public void startTimer(){
countDownTimer = new CountDownTimer(timeLeftInMilliseconds,10000) {
#Override
public void onTick(long millisUntilFinished) {
if(millisUntilFinished <= Two_Seconds){
// display your sound
}
timeLeftInMilliseconds = millisUntilFinished;
updateTimer();
}
#Override
public void onFinish() {
}
}.start();
countdownButton.setText("PAUSE");
timerRunning = true;
}
countdownText = findViewById(R.id.countdown_text);
countdownButton = findViewById(R.id.countdown_button);
countdownButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startstop();
}
});
updateTimer();
}
public void startstop(){
if(timerRunning){
stopTimer();
}else {
startTimer();
}
}
public void startTimer(){
countDownTimer = new CountDownTimer(timeLeftInMilliseconds,1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftInMilliseconds = millisUntilFinished;
updateTimer();
}
#Override
public void onFinish() {
}
}.start();
countdownButton.setText("PAUSE");
timerRunning = true;
}
public void stopTimer (){
countDownTimer.cancel();
countdownButton.setText("START");
timerRunning = false;
}
public void updateTimer (){
int minutes = (int) timeLeftInMilliseconds / 60000;
int seconds = (int) timeLeftInMilliseconds % 60000 / 1000;
String timeLeftText;
timeLeftText = "" + minutes;
timeLeftText += ":";
if(seconds <7)timeLeftText +=0;
timeLeftText += seconds;
countdownText.setText(timeLeftText);
}
}

Custom youtube player doesn't update seekbar

I created my own player layout and used Youtube api to show the video content, however when the video starts, my seekbar doesn't update and remains fix. I think that the problem is inside mSeekBarChangeListener but i'm not sure.
Here's my code:
public class ItemDetails extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener,View.OnClickListener {
private final static String TAG = "ItemDetails";
#BindView(R.id.item_title)TextView itemTitle;
#BindView(R.id.item_date)TextView itemDate;
#BindView(R.id.item_plot)TextView itemPlot;
#BindView(R.id.item_short_description)TextView itemShortDescription;
#BindView(R.id.backdop_image_details)ImageView imageBackdrop;
#BindView(R.id.tv_more)TextView tvSeeMore;
#BindView(R.id.trailer_video)YouTubePlayerView traileVideo;
#BindView(R.id.video_control)LinearLayout videoControlLayout;
#BindView(R.id.play_time)TextView mPlayTimeTextView;
#BindView(R.id.video_seekbar)SeekBar mSeekBar;
YouTubePlayer mPlayer;
private Handler mHandler = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_details);
ButterKnife.bind(this);
findViewById(R.id.play_video).setOnClickListener(this);
findViewById(R.id.pause_video).setOnClickListener(this);
mSeekBar.setMax(100);
mSeekBar.setProgress(0);
mSeekBar.setOnSeekBarChangeListener(mVideoSeekBarChangeListener);
mHandler = new Handler();
}
#OnClick(R.id.back_arrow_detail)void backArrowClick() {
onBackPressed();
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
if(youTubePlayer != null) {
mPlayer = youTubePlayer;
displayCurrentTime();
// start buffering
if(!b) {
youTubePlayer.cueVideo(trailerKey);
}
// set style and show control layout
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
videoControlLayout.setVisibility(View.VISIBLE);
youTubePlayer.setPlayerStateChangeListener(playerStateChangeListener);
youTubePlayer.setPlaybackEventListener(playbackEventListener);
}
}
private YouTubePlayer.PlaybackEventListener playbackEventListener = new YouTubePlayer.PlaybackEventListener() {
#Override
public void onPlaying() {
mHandler.postDelayed(runnable,100);
displayCurrentTime();
}
#Override
public void onPaused() {
mHandler.removeCallbacks(runnable);
}
#Override
public void onStopped() {
mHandler.removeCallbacks(runnable);
}
#Override
public void onBuffering(boolean b) {
}
#Override
public void onSeekTo(int i) {
mHandler.postDelayed(runnable,100);
}
};
private YouTubePlayer.PlayerStateChangeListener playerStateChangeListener = new YouTubePlayer.PlayerStateChangeListener() {
#Override
public void onLoading() {
}
#Override
public void onLoaded(String s) {
}
#Override
public void onAdStarted() {
}
#Override
public void onVideoStarted() {
displayCurrentTime();
}
#Override
public void onVideoEnded() {
}
#Override
public void onError(YouTubePlayer.ErrorReason errorReason) {
}
};
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Log.d(TAG,youTubeInitializationResult.toString());
}
SeekBar.OnSeekBarChangeListener mVideoSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
long lengthPlayed = (mPlayer.getDurationMillis() * progress) / 100;
mPlayer.seekToMillis((int) lengthPlayed);
seekBar.setProgress(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.play_video:
if(mPlayer != null && !mPlayer.isPlaying()) {
mPlayer.play();
}
break;
case R.id.pause_video:
if(mPlayer != null && mPlayer.isPlaying()) {
mPlayer.pause();;
}
break;
}
}
private void displayCurrentTime() {
if (null == mPlayer) return;
String formattedTime = formatTime(mPlayer.getDurationMillis() - mPlayer.getCurrentTimeMillis());
mPlayTimeTextView.setText(formattedTime);
}
private String formatTime(int millis) {
int seconds = millis / 1000;
int minutes = seconds / 60;
int hours = minutes / 60;
return (hours == 0 ? "--:" : hours + ":") + String.format("%02d:%02d", minutes % 60, seconds % 60);
}
private Runnable runnable = new Runnable() {
#Override
public void run() {
displayCurrentTime();
mHandler.postDelayed(this, 100);
}
};
}
For all who are looking for a solution:
Set the seekbar progress in within the runnable:
private Runnable runnable = new Runnable() {
#Override
public void run() {
displayCurrentTime();
//Progress in percentage
int progress = mPlayer.getCurrentTimeMillis() * 100 / mPlayer.getDurationMillis();
mSeekBar.setProgress(progress);
mHandler.postDelayed(this, 100);
}
};
Since this will start the OnSeekBarChangeListener, you need to add an additional if:
SeekBar.OnSeekBarChangeListener mVideoSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//Only when the user change the progress
if(fromUser){
long lengthPlayed = (mPlayer.getDurationMillis() * progress) / 100;
mPlayer.seekToMillis((int) lengthPlayed);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
;)
Custom youtube player CHROMELESS style - set SeekBar Progress and Seek Bar TrackingTouch Forward/backward
mSeekBar = (SeekBar) findViewById(R.id.video_seekbar);
mSeekBar.setOnSeekBarChangeListener(mVideoSeekBarChangeListener)
SeekBar.OnSeekBarChangeListener mVideoSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
long lengthPlayed = (mYouTubePlayer.getDurationMillis() * seekBar.getProgress()) / 100;
mYouTubePlayer.seekToMillis((int) lengthPlayed);
}
};
private Runnable runnable = new Runnable() {
#Override
public void run(){
displayCurrentTime();
mHandler.postDelayed(this, 100);
}
};
private void displayCurrentTime() {
if (null == mYouTubePlayer) return;
String formattedTime = formatTime(mYouTubePlayer.getDurationMillis() - mYouTubePlayer.getCurrentTimeMillis());
play_timetv.setText(formattedTime);
playPercent = (int) (((float) mYouTubePlayer.getCurrentTimeMillis()/(float) mYouTubePlayer.getDurationMillis()) * 100);
System.out.println("get youtube displayTime 2 : "+playPercent);
// update live progress
mSeekBar.setProgress(playPercent, true);
}

how to get value from countdowntimer and display into toast

i have countdown timer from 1 to 9999 if i click start button the count will start, but if click stop button i need to get current value from countdown and display that value in toast but the countdown could not stop if i click stop button please help me
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private Button startB;
public TextView ;
private final long startTime = 9999 * 1;
private final long interval = 1 *1 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startB = (Button) this.findViewById(R.id.button);
startB.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
countDownTimer = new MyCountDownTimer(startTime, interval);
text.setText(text.getText() + String.valueOf(startTime / 1));
}
public void onClick(View v) {
if (!timerHasStarted) {
countDownTimer.start();
timerHasStarted = true;
startB.setText("STOP");
} else {
/*countDownTimer.cancel();
timerHasStarted = false;
startB.setText("RESTART");*/
}
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
//text.setText("Time's up!");
countDownTimer.start();
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished / 1);
}
}
thank you
Here is my countdown timer:
QuestionCountdownTimer
public class QuestionCountdownTimer extends CountDownTimer {
private TextView remainingTimeDisplay;
private Context context;
public QuestionCountdownTimer(Context context,long millisInFuture, long countDownInterval,TextView remainingTimeDisplay) {
super(millisInFuture, countDownInterval);
this.context = context;
this.remainingTimeDisplay = remainingTimeDisplay;
}
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
String hms = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
remainingTimeDisplay.setText(hms);
}
#Override
public void onFinish() {
Toast.makeText(context,"COUNTDOWN FINISH :)",Toast.LENGTH_SHORT).show();
}
}
Note:
TextView remainingTimeDisplay
remainingTimeDisplay.setText(hms);
I use it to display the remaining time using a TextView
Here I call the timer:
//Start Quiz timer
QuestionCountdownTimer timer = new QuestionCountdownTimer(this,10000, 1000, remainingTimeDisplay);
timer.start();
-first parameter: this - I use it for context to show Toast message
-second parameter: 10000 - total time (10 sec)
-third parameter: 1000 - countdown interval (1 sec)
-last parameter: dispaly remaining time in real time
Tested and working
Create your CountDownTimer like this:
public class MyCountDownTimer extends CountDownTimer
{
private long timePassed = 0;
public MyCountDownTimer(long startTime, long interval)
{
super(startTime, interval);
}
#Override
public void onFinish()
{
//text.setText("Time's up!");
countDownTimer.start();
}
#Override
public void onTick(long millisUntilFinished)
{
timePassed++;
text.setText("" + millisUntilFinished / 1);
}
public long getTimePassed()
{
return timePassed;
}
}
And on your onClick just do:
((MyCoundDownTimer) countDownTimer).getTimePassed();
to retrieve the time and set your textview text to it.
You should use handler
private Handler tickResponseHandler = new Handler() {
public void handleMessage(Message msg) {
int time = msg.what;
//make toast or do what you want
}
}
and pass it to MyCountDownTimer constructor
private Handler handler;
public MyCountDownTimer(long startTime, long interval, Handler handler) {
super(startTime, interval);
this.handler = handler;
}
And send message
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished / 1);
Message msg = new Message();
msg.what = millisUntilFinished/1;
handler.sendMessage(msg);
}
That's all you need to do :)

SeekBar and CountDownTimer

i'm trying to use a SeekBar to control the speed of the CountDownTimer and i'm stopped in 2 issues.
1 - The DownTimerInterval doesn't reset when i change the seekbar progress...but add the progress value every time i change.
2 - I want to stop the countdown when the seekbar progress is set to 0....and it don't work.
How to fix that?
Here is my code
rolagem.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
rolagemAutomatica();
}
});
private void rolagemAutomatica() {
barra = (SeekBar)findViewById(R.exibir_musica.barraFonte);
barra.setVisibility(1);
barra.setMax(4);
barra.setProgress(0);
barra.setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
String[] VR = {"0","10","50","75","100"};
//Define crono +1 cause position 0 crash the app
int crono = Integer.parseInt(VR[progress]+1);
CountDownTimer test = new CountDownTimer(400000 , crono) {
#Override
public void onTick(long millisUntilFinished) {
scroll_letra.smoothScrollBy(0,
(int) (millisUntilFinished / 300000));
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
}
};
if(crono-1 != 0){
test.start();
}else{
test.cancel();
}
}
});
}
Hold the CountDownTimer as an instance field so that you can cancel it when you need to. If starting one with a tick timer of 0 crashes you, then just don't start one when the speed is 0.
Something like this:
barra.setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
String[] VR = {"0","10","50","75","100"};
int crono = Integer.parseInt(VR[progress]);
if (fromUser) {
this.countDownTimer.cancel();
if (crono > 0) {
this.countDownTimer = new CountDownTimer(400000 , crono) {
#Override
public void onTick(long millisUntilFinished) {
scroll_letra.smoothScrollBy(0,
(int) (millisUntilFinished / 300000));
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
}
};
if(crono-1 != 0){
test.start();
}else{
test.cancel();
}
}
}
}
});
There are some more optimizations you could do. For example, you could probably define VR as just an array of ints so you don't have to parse them, and you could keep them on the instance so you don't have to create the array over and over, etc.:
int[] VR = new int[] {0, 10, 50, 75, 100};
I found the solution for this issue.
i declare the countDownTimer as a global variable.
CountDownTimer ctimer = null;
after that...i create a method
private void timerRol(int contador) {
if (contador == 0){
Log.v(String.valueOf(contador), "Stopped");
}else{
ctimer = new CountDownTimer(400000, contador) {
#Override
public void onTick(long millisUntilFinished) {
scroll_letra.smoothScrollBy(0, (int) (millisUntilFinished / 300000));
}
#Override
public void onFinish() {
}
};
ctimer.start();
}
}
after created the method...i call it on OnCreate passing a value as parameter...and stop it after the call.
timerRol(100);
ctimer.cancel();
after that i create the seekbar and call the method when the user change the position.
barraRolagem = (SeekBar) findViewById(R.exibir_musica.barraRolagem);
barraRolagem.setVisibility(1);
barraRolagem.setMax(5);
barraRolagem.setProgress(0);
final int[] crono = { 0, 750, 500, 100, 50, 1};
barraRolagem.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
if((crono[progress] == 0)) {
ctimer.cancel();
}else{
Log.v(String.valueOf(crono[progress]), "valor do crono");
ctimer.cancel();
timerRol(crono[progress]);
}
}
});

Countdown timer with pause and resume

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();
}

Categories

Resources