I'm making a simple app where I start a countdown timer e.g. 25 to 0 and when the timer expires it shows a template.But when my mobile is locked timer will be paused and when i unlocked it will resume .what can i do for continues timer ??
public class MyActivity extends Activity {
TextView tvCountDown;
MyCount counter;
long countDownInterval = 1000;
#Override
public void onCreate(Bundle savedInstanceState) {
setTheme(android.R.style.Theme_Light_NoTitleBar_Fullscreen);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auth);
tvCountDown = (TextView) findViewById(R.id.tvCountDown);
counter = new MyCount(6000, countDownInterval);
counter.start();
}
public class MyCount extends CountDownTimer
{
public MyCount(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
public void onTick (long millisUntilFinished)
{
Log.v("test","onTick Seconds: "+millisUntilFinished+" : "+(millisUntilFinished / 1000));
tvCountDown.setText ( formatTime(millisUntilFinished));
System.out.print("");
}
public void onFinish() {
tvCountDown.setText("done!");
}
public String formatTime(long millis)
{
String output = "00:00:00";
long seconds = millis / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
seconds = seconds % 60;
minutes = minutes % 60;
hours = hours % 60;
String secondsD = String.valueOf(seconds);
String minutesD = String.valueOf(minutes);
String hoursD = String.valueOf(hours);
if (seconds < 10)
secondsD = "0" + seconds;
if (minutes < 10)
minutesD = "0" + minutes;
if (hours < 10)
hoursD = "0" + hours;
output = hoursD + " : " + minutesD + " : " + secondsD;
return output;
}
}
Just call .cancel() method when your activity/fragment going to destroy.
If you want to pause/resume yout timer go for this answer;
Related
How to make this action happen at the end of the time when there are still 5 seconds left.
This is the code of the action that I want to do when there are 5 seconds left from the timer:
mTextViewCountDown.setTextColor(Color.RED);
zooming_second = AnimationUtils.loadAnimation(Level1.this, R.anim.watch_zoo);
mTextViewCountDown.startAnimation(zooming_second);
soundPlay(watch);
In this method:
//variable start
private static final long START_TIME_IN_MILLIS = 60000;
private TextView mTextViewCountDown;
private CountDownTimer mCountDownTimer;
private boolean mTimerRunning;
private long mTimeLeftInMillis = START_TIME_IN_MILLIS;
//variable end
private void startTimer() {
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted = String.format(Locale.ENGLISH, "%02d:%02d", minutes, seconds);
mTextViewCountDown.setText(timeLeftFormatted);
mTimerRunning = true;
}
#Override
public void onFinish() {
mTimerRunning = false;
TimeOutDialog();
soundPlay(time_out_sound);
mediaPlayer1.stop();
tadam_false.stop();
tadam_true.stop();
}
}.start();
}
private void pauseTimer () {
mCountDownTimer.cancel();
mTimerRunning = false;
}
Inside onTick(long) method simply check how many seconds are left. And if it is five, trigger your action.
EDIT
My approach to hitting the right time would be something like this:
if (Math.abs(mTimeLeftInMillis - 5000) < 100) {
// start the animation
}
This would avoid issues with if (mTimeLeftInMillis == 5000) as it gives it some buffer. It's needed because it will not trigger at exactly 5000 milliseconds.
Thanks! I did it like this:
if (mTimeLeftInMillis <= 6000){
mTextViewCountDown.setTextColor(Color.RED);
zooming_second = AnimationUtils.loadAnimation(Level1.this,
R.anim.watch_zoo);
mTextViewCountDown.startAnimation(zooming_second);
soundPlay(watch);
}
I am an absolute beginner and was trying to code a Count-up-timer app that will run in the background, in other words when the app is closed from overview or when the back button is pressed, the timer will still appear to continue on the corrected time the next time the app is opened. I tried to do this by using SharedPreferences.
An error that I run into is that when I launch the emulator, the timer does not start at 00:00:00 as it should, however, it starts at random times. Here is a screenshot
public class MainActivity extends AppCompatActivity {
TextView timerText;
TextView dayText;
Button startStopButton;
Timer timer;
TimerTask timertask;
Double time = 0.0;
Double mEndTime = 0.0;
Double startingSysTime = 0.0;
Double timeGap = 0.0;
public static final String SHARED_PREFS ="sharedPrefs";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerText = (TextView) findViewById(R.id.timerText);
startStopButton = (Button) findViewById(R.id.startStopButton);
dayText = (TextView) findViewById(R.id.dayText);
timer = new Timer();
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
time = Double.longBitsToDouble(prefs.getLong("mTimeValue", Double.doubleToLongBits(0.0)));
mEndTime = Double.longBitsToDouble(prefs.getLong("onDestr_SysTime", Double.doubleToLongBits(0.0)));
if(mEndTime==0.0){
startingSysTime = 0.0;
}else{
startingSysTime = (double) (System.currentTimeMillis());
}
timeGap = startingSysTime - mEndTime;
time += timeGap;
startTimer();
}
#Override
protected void onStop() {
super.onStop();
Log.i("TIMEGAP", "onStop called");
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("mTimeValue", Double.doubleToRawLongBits(time)); //saves the time value
editor.putLong("onDestr_SysTime", Double.doubleToRawLongBits(System.currentTimeMillis())); //saves the CurrentSystemTime when onStop is invoked
editor.apply();
}
private void startTimer() {
timertask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
time++;
timerText.setText(getTimerText());
dayText.setText(getDayText());
}
});
}
};
timer.scheduleAtFixedRate(timertask, 0, 1000);
}
private String getDayText() {
int rounded = (int) Math.round(time);
int days = (rounded / 86400);
return formatDay(days);
}
private String formatDay(int days) {
String pluralDays;
if (days == 1) {
pluralDays = " Day";
} else {
pluralDays = " Days";
}
return days + pluralDays;
}
private String getTimerText() {
int rounded = (int) Math.round(time);
int seconds = ((rounded % 86400) % 3600) % 60;
int minutes = ((rounded % 86400) % 3600) / 60;
int hours = ((rounded % 86400) / 3600);
return formatTime(seconds, minutes, hours);
}
private String formatTime(int seconds, int minutes, int hours) {
return String.format("%02d", hours) + " : " + String.format("%02d", minutes) + " : " + String.format("%02d", seconds);
}
EDIT: Problem fixed, I simply had to convert timeGap to seconds by dividing it by 1000
timeGap = (startingSysTime - mEndTime)/1000;
Try this way
Handler.postDelayed(new Runnable{
//Todo write your code here
handler.postdelayed(this,1000);
},1000);
Start where you need
long starttime;
start time = System.currentTimeMilisecond();
End where you need
long currtime = System.currentTimeMilisecond() - startime;
}
According to your question try to convert this millisecond in your format which you need. Store long value in shared preference if you want to manage this on app close also
I have an app that has one countdown timer that should show up the same for every user when they open the app. In order to do this, I have based the time that the users' phones show on Epoch time. I do the following calculations to (what I thought would...) ensure that each phone shows the same time, and that the countdown clock is continuous and accurate. However, every time I open the app up, the clock is at a totally different time, when I think it should be continuously counting down and resetting. What's wrong? I have included my code below:
private static final int COUNTDOWN_DURATION = 30; //time in seconds
private static final long BASE_TIME = 1470729402L; //an arbitrary Epoch time that I have picked as a reference point
private TextView tvTimer;
private Long currentTimeMillis;
private int finalTime;
private boolean firstTime;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
//set up basics
...
//set up timer
tvTimer = (TextView) findViewById(R.id.tvTimer);
firstTime = true;
setCurrentTime();
}
private void setCurrentTime() {
currentTimeMillis = System.currentTimeMillis();
long currentTimeSecs = currentTimeMillis/1000;
long timeDiff = currentTimeSecs - BASE_TIME;
//determines what spot the countdown timer is at when the app is started
finalTime = (int) (timeDiff % COUNTDOWN_DURATION);
resetTimer();
}
public void resetTimer(){
if (firstTime) {
CountDownTimer countDownTimer = new CountDownTimer(finalTime * 1000, 1000) {
public void onTick(long millisUntilFinished) {
tvTimer.setText(" " + millisUntilFinished / 1000 + " ");
}
public void onFinish() {
resetTimer();
}
};
countDownTimer.start();
firstTime = false;
}
else {
CountDownTimer countDownTimer = new CountDownTimer(COUNTDOWN_DURATION * 1000, 1000) {
public void onTick(long millisUntilFinished) {
tvTimer.setText(" " + millisUntilFinished / 1000 + " ");
}
public void onFinish() {
resetTimer();
}
};
countDownTimer.start();
}
}
I need to update time every second on a countdown timer which counts down to Christmas.
How do I update the time in my text view.I do not have the code in the onCreate method.
here is some of my code. When I run the code it gives the exact time, but it does not countdown live on screen. Any ideas?
Edit: the readThisPeriod is for calculating the time left until Christmas.
public void DateCalculator() {
Calendar today = Calendar.getInstance();
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH, 25);
thatDay.set(Calendar.MONTH, 11); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 2014);
thatDay.set(Calendar.HOUR, 0);
thatDay.set(Calendar.MINUTE, 0);
thatDay.set(Calendar.SECOND, 0);
thatDay.set(Calendar.AM_PM, 0);
System.out.println(thatDay.getTime());
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(1);
scheduledExecutorService.scheduleAtFixedRate(new ReadThisPeriod(thatDay), 0, 1,
TimeUnit.SECONDS);
long diff = (thatDay.getTimeInMillis() - today.getTimeInMillis()) / 1000;
long days = diff / (60 * 60 * 24);
long hours = diff / (60 * 60) % 24;
long minutes = diff / 60 % 60;
long seconds = diff % 60;
daysBox = (TextView) findViewById(R.id.s1Days);
daysBox.setText("" + "" + days + "" + hours + "" + minutes + "" + seconds + " );
}
Start a CountDownTimer :
long endTime = thatDay.getTimeInMillis();
new MyCountDownTimer(endTime-System.currentTimeMillis(),1000).start();
Here you go:
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
textView.setText("Happy Christmas!");
}
#Override
public void onTick(long millis) {
int SECOND = 1000;
int MINUTE = 60 * SECOND;
int HOUR = 60 * MINUTE;
int DAY = 24 * HOUR;
StringBuffer text = new StringBuffer();
if (millis > DAY) {
text.append(millis / DAY).append(" days ");
millis %= DAY;
}
if (millis > HOUR) {
text.append(millis / HOUR).append(" hours ");
millis %= HOUR;
}
if (millis > MINUTE) {
text.append(millis / MINUTE).append(" minutes ");
millis %= MINUTE;
}
if (millis > SECOND) {
text.append(millis / SECOND).append(" seconds ");
millis %= SECOND;
}
textView.setText(text);
}
}
import android.app.Activity;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.util.Calendar;
public class MainActivity extends Activity {
private TextView daysBox;
private boolean running;
private Calendar thatDay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
daysBox = (TextView) findViewById(R.id.main_day);
thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH, 25);
thatDay.set(Calendar.MONTH, 11); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 2014);
thatDay.set(Calendar.HOUR, 0);
thatDay.set(Calendar.MINUTE, 0);
thatDay.set(Calendar.SECOND, 0);
thatDay.set(Calendar.AM_PM, 0);
startDateCalculator();
}
protected void onPause() {
super.onPause();
running = false;
}
protected void onResume() {
super.onResume();
running = true;
}
private class CountdownTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... args) {
while (running) {
try {
Thread.sleep(1000);
} catch (Exception e) {
}
publishProgress();
}
return null;
}
protected void onProgressUpdate(Void... res) {
super.onProgressUpdate(res);
long diff = (thatDay.getTimeInMillis() - System.currentTimeMillis()) / 1000;
long days = diff / (60 * 60 * 24);
long hours = diff / (60 * 60) % 24;
long minutes = diff / 60 % 60;
long seconds = diff % 60;
daysBox.setText("" + "" + days + "d " + hours + ":" + minutes + ":" + seconds + " ");
}
}
public void startDateCalculator() {
new CountdownTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
long diff = (thatDay.getTimeInMillis() - today.getTimeInMillis()) / 1000;
long total=diff;
mTimer=new CountDownTimer(total, 1000) {
public void onTick(long millisUntilFinished) {
diff--;
daysBox.setText(convertSecondToHHMMString(diff));
}
public void onFinish() {
System.out.println("Happy Chrismas");
}
}.start();
private String convertSecondToHHMMString(long secondtTime){
TimeZone tz = TimeZone.getTimeZone("UTC");
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
df.setTimeZone(tz);
String time = df.format(new Date(secondtTime*1000L));
return time;
}
I’m new to Java language but worked with C language previously. I tried many ways to solve the following problem but couldn’t so I need help.
I’m trying to do the following:
•Set 5 minute timer (counter) as default so starts when Start_button is pressed.
•If Start_button is not pressed and the user presses Up_button /Down_button then display timer options on screen; 5, 10 and 15minutes and if the user presses Starts_button it starts to count down the timer chosen.
•While timer is running;
•If Up_button /Down_button is pressed once then reset timer and show previous time setting i.e. 5, 10 or 15minutes.
•If Up_button /Down_button is pressed again then display timer options on screen and if the user presses Starts_button it starts the timer chosen.
At the moment; the timer is working once Start is pressed it counts down the 5 minutes. But I do not know the best way to display the timer options and also start the chosen timer.
Your help is appreciated, thank you very much in advance.
As mentioned above; I’m in the process of learning Java programming so take it easy on me ;-) and show me the code that you think is best for this problem please
This is what I did so far:
public class Test extends Activity {
// Display Counter Variables
public static Button Up, Down, Green;
TextView timeDisplay;
MyCount counter, counter1, counter2;
int state = 0;
int length = 300000; //5minutes
int length1 = 600000; //10minutes
int length2 = 900000; //15minutes
long startTime = 0;
long currentTime = 0;
long timeElapsed = 0;
long timeRemaining = 0;
long prevTimeRemaining = 0;
boolean up_pressed = false;
boolean down_pressed = false;
private boolean timerStarted=false;
Button start;
public String formatTime(long millis) {
String output = "";
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;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
timeDisplay = (TextView) findViewById(R.id.timer);
counter = new MyCount (length, 1000);
counter1 = new MyCount (length1, 1000);
counter2 = new MyCount (length2, 1000);
start = (Button) findViewById(R.id.Button);
Up = (Button)findViewById(R.id.Yellow);
Down = (Button)findViewById(R.id.Blue);
start.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
switch (state) {
case 0:
startTime = System.currentTimeMillis();
counter.start();
timerStarted=true;
start.setText(R.string.pause);
state=1;
break;
case 1:
// pause
currentTime = System.currentTimeMillis();
timeElapsed = currentTime - startTime;
if (prevTimeRemaining == 0)
timeRemaining = length - timeElapsed;
else
timeRemaining = prevTimeRemaining - timeElapsed;
counter.cancel();
timeDisplay.setText("" + formatTime(timeRemaining));
start.setText(R.string.resume);
prevTimeRemaining = timeRemaining;
// resume
counter = new MyCount(timeRemaining, 1000);
state = 0;
break;
case 2:
prevTimeRemaining = 0;
timerStarted=false;
counter = new MyCount(length, 1000);
start.setText(R.string.start);
timeDisplay.setText(R.string.timer);
state = 0;
}
}
});
Up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
down_pressed=true;
if(up_pressed=true && timerStarted==true
|| timerStarted==false){
//Display timer (increment i.e. show 5min --> 10min ..> 15min)
//start timer chosen by user
}
}
});
Down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
down_pressed=true;
if(down_pressed=true && timerStarted==true
|| timerStarted==false){
//Display timer (decrement i.e. show 15min --> 10min ..> 5min)
//start timer chosen by user
}
}
});
}
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
public void onFinish() {
timeDisplay.setText("done!");
state = 2;
start.setText(R.string.restart);
}
public void onTick (long millisUntilFinished) {
timeDisplay.setText ("Left: " + formatTime(millisUntilFinished));
}
}
}
I don't think you need a new Class for this.
I would simply create a global variable, eg.
private CountDownTimer myCount;
I would recommend putting this into a method like
private void setTimer(long countdownMs, long tickMs) {
CountDownTimer myCount = new CountDownTimer(countdownMs,tickMs) {
/// TODO
}.start();
}
If you need to restart the timer you can call
myCount.cancel()
setTimer(...);
Comment if you need more details :)