How to display the timer in android - android

I want to display the timer in TextView in the format of like [ 19:59].so when i click the start button ,the timer will display like this for example,i want to set upto 20 mintues,it will display like [19:58][19:87].can anyone give some ideas or example code?

You can use the CountDownTimer.
http://developer.android.com/reference/android/os/CountDownTimer.html
TextView _tv = (TextView) findViewById( R.id.textView1 );
new CountDownTimer(20*60000, 1000) {
public void onTick(long millisUntilFinished) {
_tv.setText("seconds remaining: " +new SimpleDateFormat("mm:ss:SS").format(new Date( millisUntilFinished)));
}
public void onFinish() {
_tv.setText("done!");
}
}.start();
To cancel just call cancel on the timer.
public final void cancel()
Cancel the countdown.

package com.example.testproject;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity {
public int seconds = 60;
public int minutes = 10;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView tv = (TextView) findViewById(R.id.main_timer_text);
tv.setText(String.valueOf(minutes)+":"+String.valueOf(seconds));
seconds -= 1;
if(seconds == 0)
{
tv.setText(String.valueOf(minutes)+":"+String.valueOf(seconds));
seconds=60;
minutes=minutes-1;
}
}
});
}
}, 0, 1000);
}
}

//start button click
CountDown timer = new CountDown(180000, 1000);
timer.start();
//stop button click
timer.stop();
//countdown class
public class CountDown extends CountDownTimer {
public CountDown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
long ms = millisUntilFinished;
String text = String.format("%02d\' %02d\"",
TimeUnit.MILLISECONDS.toMinutes(ms) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(ms)),
TimeUnit.MILLISECONDS.toSeconds(ms) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(ms)));
textViewTimer.setText(text);
}
#Override
public void onFinish() {
textViewTimer.setText("ffinish");
}
}

do it this way activity_timer.xml
<android.support.v7.widget.LinearLayoutCompat
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Chronometer
android:id="#+id/chronometer2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.v7.widget.LinearLayoutCompat>
And in Activity
public class TimerActivity extends AppCompatActivity {
private Chronometer chronometer2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
chronometer2 = findViewById(R.id.chronometer2);
chronometer2.start();
}
}
You can also use stop
chronometer2.stop();
Re Start
chronometer2.setBase(SystemClock.elapsedRealtime());
chronometer2.start();

Here I have use Timer class to display timer
public class FourthActivity extends AppCompatActivity {
Button startButton, pauseButton;
TextView timerValue;
Timer timer;
int seconds = 0, minutes = 0, hour = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fourth);
bindView();
timer = new Timer();
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (seconds == 60) {
timerValue.setText(String.format("%02d", hour) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
minutes = seconds / 60;
seconds = seconds % 60;
hour = minutes / 60;
}
seconds += 1;
timerValue.setText(String.format("%02d", hour) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
}
});
}
}, 0, 1000);
}
});
}
private void bindView() {
timerValue = (TextView) findViewById(R.id.timerValue);
startButton = (Button) findViewById(R.id.startButton);
}
}
In layout, there are one TextView and one Button to start timer. I have use Timer class method scheduleAtFixedRate. Time will be displayed in hh:mm:ss form.

This can be done using cronometer, the most main reason is supporting API 1+, which is quite impressive rather than TextClock, which supports API 17+.
You can do lots of other things with cronometer. for example you can set start time in it
chronometer.setBase(SystemClock.elapsedRealtime());
You can also learn about it more here.

I made code for timer display in textView.The formate is for e.g:- 02:59:00
You can follow this link to get the Step By Step Code.
https://stackoverflow.com/a/58316149/11613683

Related

How I can make chess-timer clock in android

I am a beginner in android, and I want to make a simple chess-timer clock. Here, I have taken two buttons. If I click on the first one the second button should start a countdown or vice-versa. But pause button is not working properly it pauses only one time second time it will not pause. Here I attached my code.
package com.example.jaydeep.practicework.chessClock;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.jaydeep.practicework.R;
public class Main8Activity extends AppCompatActivity {
Button button11,button22;
CountDownTimer count,count1;
int s1=60,s2=60;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main8);
button11 = (Button) findViewById(R.id.Button11);
button22 = (Button) findViewById(R.id.Button22);
button11.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
button11.setEnabled(false);
reverseTimer1(s2, button22);
}
});
button22.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
button22.setEnabled(false);
reverseTimer(s1, button11);
}
});
}
public void reverseTimer(int Seconds,final Button button){
button11.setEnabled(true);
count= new CountDownTimer(Seconds* 1000+1000, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000);
s1=seconds;
int minutes = seconds / 60;
seconds = seconds % 60;
button.setText( String.format("%02d", minutes)
+ ":" + String.format("%02d", seconds));
}
public void onFinish() {
button.setText("Time Up!!!");
}
};
count.start();
}
public void reverseTimer1(int Seconds,final Button button){
button22.setEnabled(true);
count1= new CountDownTimer(Seconds* 1000+1000, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000);
s2=seconds;
int minutes = seconds / 60;
seconds = seconds % 60;
button.setText( String.format("%02d", minutes)
+ ":" + String.format("%02d", seconds));
}
public void onFinish() {
button.setText("Time Up!!!");
}
};
count1.start();
}
}
cancel();
You need this code
if(isPaused || isCanceled)
{
//If the user request to cancel or paused the
//CountDownTimer we will cancel the current instance
cancel();
}
This link should help you understand:
https://android--examples.blogspot.com.au/2015/04/android-countdowntimer-start-pause.html

I am not able to stop the Android Timer

I am using following code to run a timer in my Android App.
I want to stop the Timer exactly when the time reaches to
1 Minute
2 Minute
3 Minute
and so on.
But I am not able to understand how to do it.
Any Help Will be appreciated.
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView timerTextView;
long startTime = 0;
//runs without a timer by reposting this handler at the end of the runnable
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerTextView.setText(String.format("%d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerTextView = (TextView) findViewById(R.id.text);
Button b = (Button) findViewById(R.id.button);
b.setText("start");
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button b = (Button) v;
if (b.getText().equals("stop")) {
timerHandler.removeCallbacks(timerRunnable);
b.setText("start");
} else {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
b.setText("stop");
}
}
});
}
#Override
public void onPause() {
super.onPause();
timerHandler.removeCallbacks(timerRunnable);
Button b = (Button)findViewById(R.id.button);
b.setText("start");
}
}
Why not use the CountDownTimer class?
You can simply instantiate it as:
int bigTime = 1000000000;
//1000 is ms after which the timer ticks (that is, the method gets called and so, you can update your view)
CountDownTimer countDownTimer = new CountDownTimer(bigTime, 1000) {
public void onTick(long millisUntilFinished) {
updateTime();
//you can write the code to update your view in this method
}
#Override
public void onFinish() {
Log.i("Get a life bro..."," 31 years have passed!");
}
};
Now, in your onCreate() method, according to the clicklisteners on your start/stop button, you can simply start or stop the timer:
countDownTimer.start();
if(seconds == 0 && minutes > 0) {
// get the values of seconds and minutes from the view.
countDownTimer.cancel();
}
Just in case you want to pause the timer and start from the paused time, you can store the value of the time in milliseconds, stop the timer and restart it after adding the value you stored.

how to start a countdown timer on activity start without any action performed?

I have written a program for a countdown timer but the countdown starts only on button click , but i want it to start without the button click , can anyone suggest me how to do it without the button click ?
Here is the code for countdown timer
public class MainActivity extends ActionBarActivity {
CountDownTimer countDownTimer;
boolean timehasstarted = false;
Button btnStart;
TextView timer;
long startTime = 30 * 1000;
long interval = 1 * 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.button1);
timer = (TextView) findViewById(R.id.timer);
timer.setText(timer.getText() + String.valueOf(startTime / 1000));
btnStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!timehasstarted) {
countDownTimer.start();
timehasstarted = true;
timer.setText("Stop");
} else {
countDownTimer.cancel();
timehasstarted = false;
timer.setText("Restart");
}
}
});
countDownTimer = new CountDownTimer(startTime, interval) {
#Override
public void onTick(long millisUntilFinished) {
timer.setText("" + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
timer.setText("Time's Up!");
}
};
}
Move your timer code to onCreate() method of the Activity instead of the onClick() method
This will start the timer on activity start.
And also you can use timer.cancel() to cancel the timer when the activity is stopped or not currently active
if you want to turn on the countdown after a particular time say after 2 sec then you can use TimerTask for this for exmaple :
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
}
}, 2000);

How Automatically Countdown Timer in Android?

I'm working with timer function in Android, I have the code of 1 to up timer. Please help me make it a countdown timer without clicking a button?
public class MainActivity extends Activity {
public int time = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView tv = (TextView) findViewById(R.id.main_timer_text);
tv.setText(String.valueOf(time));
time += 1;
}
});
}
}, 0, 1000);
}
You can use CountDownTimer for this
new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilEnd) {
mTextView.setText(String.valueOf(millisUntilEnd / 1000));
}
public void onFinish() {
mTextView.setText("done");
}
}.start();
This will update your time TextView each second for 20 seconds.

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