synchronized countdown timer- android development - java

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

Related

How do you find the time difference between onStop and onCreate lifecycle callbacks?

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

android - countdown timer is not canceling

In my app the user gets a point, when he clicks a button within 5 seconds. After that the timer should be canceled and restart. The problem I have is that the timer countinues counting down until it restarts. Is it set up wrong, or doesn't cancel(); stop the timer at all?
public class MainActivity extends AppCompatActivity {
Button btn;
TextView text;
TextView scoretv;
private static final String FORMAT = "%02d:%02d";
public int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scoretv = (TextView) findViewById(R.id.textView3);
btn = (Button) findViewById(R.id.button1);
text = (TextView) findViewById(R.id.textView2);
}
public void onClick(View view) {
score++;
scoretv.setText(String.valueOf(score));
load();
}
private void load() {
// TODO Auto-generated method stub
new CountDownTimer(5000, 10) { // adjust the milli
// seconds here
public void onTick(long millisUntilFinished) {
text.setText(""
+ String.format(
"%02d:%03d",
TimeUnit.MILLISECONDS
.toSeconds(millisUntilFinished)
- TimeUnit.MINUTES
.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millisUntilFinished)),
TimeUnit.MILLISECONDS
.toMillis(millisUntilFinished)
- TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS
.toSeconds(millisUntilFinished))));
}
public void onFinish() {
text.setText("GameOver.");
cancel();
}
}.start();
}
}
Because you're calling cancel() in onFinish, the timer won't stop when the user clicks the button. What will happen instead is that the button will start a 5 second CountDownTimer and at the end of the timer, cancel() will be called. But what's the point of cancelling a timer when it's already finished?
To fix this, I'd suggest making a global instance of a CountDownTimer object, instantiate it in the onCreate method, and cancel it in the onClick method.
First, add this to your global scope,
CountDownTimer timer;
Then, add what you originally had before in the load method to your onCreate,
timer = new CountDownTimer(5000, 10) { // adjust the milli
// seconds here
public void onTick(long millisUntilFinished) {
text.setText(""
+ String.format(
"%02d:%03d",
TimeUnit.MILLISECONDS
.toSeconds(millisUntilFinished)
- TimeUnit.MINUTES
.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millisUntilFinished)),
TimeUnit.MILLISECONDS
.toMillis(millisUntilFinished)
- TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS
.toSeconds(millisUntilFinished))));
}
public void onFinish() {
text.setText("GameOver.");
//cancel(); <-this is redundant
}
}.start();
And call timer.cancel() in your onClick method,
public void onClick(View view) {
score++;
scoretv.setText(String.valueOf(score));
//load(); <-unnecessary
timer.cancel();
}
Lastly, I'd suggest getting rid of load since it's sort of unnecessary at this point.
Define variable
private final long timeLeftInMillis=60000;
Create class
public void startCountDown() {
countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
//Edit text set with time remaining
int seconds = (int) (millisUntilFinished / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
etime.setText( String.format("%02d", minutes)
+ ":" + String.format("%02d", seconds));
}
#Override
public void onFinish() {
}
}.start();
}
I used this in a quiz app to reset timer when an answer is given. Therefore I called timer from the class that I used to add a new question.
private void newQuestion(){
if (countDownTimer!=null){
countDownTimer.cancel();
}
getNextQuestion();
}

How to start a timer using another timer in Android Studio

I'm a novice in Java (Less than 3 months experience), and for a project I've been working on I need to create a timer.
I've done this before, however I do not know how to do one thing.
I want to start a timer when a second timer ends. What I mean by this is that instead of using a start/stop button to start a timer, I want to have a second timer (that starts at 3 seconds) determine when the first timer starts. For example, if the first timer is at 30 seconds, it will start counting down when the second timer finishes counting down from 3-0.
I know there has to be other classes or methods/listeners to do this, but as I've stated earlier, it's my first time ever working with Java (I normally use C++).
Any help/guidance/code on how to achieve this would be awesome. Here is the code I was toying around with to try and achieve this.
Java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.os.CountDownTimer;
public class Timer extends AppCompatActivity
{
TextView timer;
TextView timerStart;
Button multi;
int track;
int seconds;
CountDownTimer countDownTimer;
CountDownTimer start;
View.OnClickListener btnListen = new View.OnClickListener(){
#Override
public void onClick(View v)
{
switch(v.getId())
{
case R.id.multi : start();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
timer = (TextView) findViewById(R.id.timer);
timerStart = (TextView) findViewById(R.id.timerStart);
multi = (Button) findViewById(R.id.multi);
multi.setOnClickListener(btnListen);
multi.setText("Start");
}
public void start_timer()
{
track = 3;
start = new CountDownTimer(3*1000,1000) {
#Override
public void onTick(long millisUntilFinished) {
timerStart.setText("" + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
timerStart.setText("Begin");
track = 0;
}
}.start();
seconds = 30;
if (timerStart.getText().equals("Begin"))
{
start.cancel();
countDownTimer = new CountDownTimer(30 * 1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timer.setText("" + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
timer.setText("BEEP");
}
}.start();
}
else
{
System.out.println("Nothing");
}
}
public void start()
{
start_timer();
/*seconds = 30;
if (timerStart.getText().equals("Begin"))
{
countDownTimer = new CountDownTimer(seconds * 1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timer.setText("" + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
timer.setText("BEEP");
}
}.start();
}*/
}
}
Again, this is just something I'm toying around with. If there is a different way to do this (Like using a Runnable or Handler), then I'm open to it. My goal is to learn Java.
How about this? I modified CountDownTimer to enable to be chained.
public abstract class ChainedCountDownTimer {
/**
* Millis since epoch when alarm should stop.
*/
private final long mMillisInFuture;
/**
* The interval in millis that the user receives callbacks
*/
private final long mCountdownInterval;
private long mStopTimeInFuture;
/**
* boolean representing if the timer was cancelled
*/
private boolean mCancelled = false;
/**
* First timer in chaining
*/
private ChainedCountDownTimer first;
/**
* Next timer
*/
private ChainedCountDownTimer next;
/**
* #param millisInFuture The number of millis in the future from the call
* to {#link #start()} until the countdown is done and {#link #onFinish()}
* is called.
* #param countDownInterval The interval along the way to receive
* {#link #onTick(long)} callbacks.
*/
public ChainedCountDownTimer(long millisInFuture, long countDownInterval) {
mMillisInFuture = millisInFuture;
mCountdownInterval = countDownInterval;
first = this;
}
/**
* Cancel the countdown.
*/
public synchronized final void cancel() {
first.mCancelled = true;
mHandler.removeMessages(MSG);
}
public void start() {
first.startInternal();
}
/**
* Start the countdown.
*/
public synchronized final ChainedCountDownTimer startInternal() {
mCancelled = false;
if (mMillisInFuture <= 0) {
onFinish();
if (next != null) {
next.startInternal();
}
return this;
}
mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
mHandler.sendMessage(mHandler.obtainMessage(MSG));
return this;
}
/**
* Callback fired on regular interval.
* #param millisUntilFinished The amount of time until finished.
*/
public abstract void onTick(long millisUntilFinished);
/**
* Callback fired when the time is up.
*/
public abstract void onFinish();
public ChainedCountDownTimer setNext(ChainedCountDownTimer next) {
this.next = next;
next.first = this.first;
return this.next;
}
private static final int MSG = 1;
// handles counting down
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
synchronized (ChainedCountDownTimer.this) {
if (first.mCancelled) {
return;
}
final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();
if (millisLeft <= 0) {
onFinish();
if (next != null) {
next.startInternal();
}
} else if (millisLeft < mCountdownInterval) {
// no tick, just delay until done
sendMessageDelayed(obtainMessage(MSG), millisLeft);
} else {
long lastTickStart = SystemClock.elapsedRealtime();
onTick(millisLeft);
// take into account user's onTick taking time to execute
long delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime();
// special case: user's onTick took more than interval to
// complete, skip to next interval
while (delay < 0) delay += mCountdownInterval;
sendMessageDelayed(obtainMessage(MSG), delay);
}
}
}
};
}
You can use it like this.
ChainedCountDownTimer timer1 = new ChainedCountDownTimer(3 * 1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.d(TAG, "timer1 onTick");
}
#Override
public void onFinish() {
Log.d(TAG, "timer1 onFinish");
}
};
ChainedCountDownTimer timer2 = new ChainedCountDownTimer(30 * 1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.d(TAG, "timer2 onTick");
}
#Override
public void onFinish() {
Log.d(TAG, "timer2 onFinish");
}
};
timer1.setNext(timer2).start();

Pausing a CountDownTimer whilst another one runs - Android

I have two countdown timers in my program, a longer one (120 sec) and a shorter one (3.5 sec). I want the 120 second timer to be paused whilst the 3.5 second timer is running, and for the longer timer to continue running whenever the 3.5 second timer isn't running. So the program starts with the 120 sec remaining whilst the 3.5 sec one runs, then when the 3.5 sec one runs the 120 sec one will start and only pause when the 3.5 sec one runs again (once users presses enter.) How would I do this?
final CountDownTimer loop = new CountDownTimer(3500, 1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
number.setVisibility(View.GONE);
final TextView prompt = (TextView) findViewById(R.id.prompt);
prompt.setVisibility(View.VISIBLE);
prompt.setText(" Enter the number");
final EditText input = (EditText) findViewById(R.id.enterAnswer);
input.setVisibility(View.VISIBLE);
input.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
Editable answer = input.getText();
int finalAnswer = Integer.parseInt(String.valueOf(answer));
int finalLoadG1 = Integer.parseInt(String.valueOf(number.getText()));
input.setVisibility(View.GONE);
prompt.setVisibility(View.GONE);
if (finalAnswer == finalLoadG1) {
score++;
}
number.setVisibility(View.VISIBLE);
if (score>=0 && score<=2){
int loadG1 = generateG1.nextInt(89999)+10000;
number.setText(""+loadG1);
}
else if (score>=3 && score<=5){
int loadG1 = generateG1.nextInt(899999)+100000;
number.setText(""+loadG1);
}
else if (score>=6 && score<=9){
int loadG1 = generateG1.nextInt(8999999)+1000000;
number.setText(""+loadG1);
}
else if (score>=10 && score<=14){
int loadG1 = generateG1.nextInt(89999999)+10000000;
number.setText(""+loadG1);
}
else if (score>=15 && score<=20){
int loadG1 = generateG1.nextInt(899999999)+100000000;
number.setText(""+loadG1);
}
else if (score>=21) {
int loadG1 = generateG1.nextInt((int) 8999999999L)+1000000000;
number.setText(""+loadG1);
}
input.getText().clear();
start();
return true;
default:
}
}
return false;
}
});
}
}.start();
new CountDownTimer(120000, 1000) {
#Override
public void onTick (long millisUntilFinished) {
}
#Override
public void onFinish() {
TextView result = (TextView) findViewById(R.id.outcome);
result.setText("Score: "+ score);
TextView prompt = (TextView) findViewById(R.id.prompt);
prompt.setVisibility(View.GONE);
final EditText input = (EditText) findViewById(R.id.enterAnswer);
input.setVisibility(View.GONE);
loop.cancel();
number.setVisibility(View.GONE);
}
}.start();
I have asked this before, but was not given a valid answer unfortunately. Would be grateful if anyone is capable of answering this question. Please feel free to insert any code that'll help explain your answer. Many thanks in advance.
Ok, I will try to give an example, but no guarantee that this is exactly what you need:
create a global variable and the CountDownTimer objects:
Long remainingTime = 120000L;
ThreePointFiveSecondsTimer mThreePointFiveSecondsTimer;
HundredTwentySecondsTimer mHundredTwentySecondsTimer;
create the 120 seconds timer:
public class HundredTwentySecondsTimer extends CountDownTimer {
public HundredTwentySecondsTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
}
}
create the 3.5 seconds timer:
public class ThreePointFiveSecondsTimer extends CountDownTimer {
public ThreePointFiveSecondsTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
remainingTime = millisUntilFinished;//set the remaining time
}
#Override
public void onFinish() {
//start the 120 second countdowntimer again
mHundredTwentySecondsTimer = new MyCountDownTimer(remainingTime, 1000);
mHundredTwentySecondsTimer.start();
}
}
start the 120 second timer:
mHundredTwentySecondsTimer = new MyCountDownTimer(remainingTime, 1000);
mHundredTwentySecondsTimer.start();
Then, at any time, you decide to start the 3.5 timer:
mThreePointFiveSecondsTimer = new ThreePointFiveSecondsTimer (3500, 1000);
mThreePointFiveSecondsTimer.start();
mHundredTwentySecondsTimer.cancel();
mHundredTwentySecondsTimer = null;
That´s just the idea behind, but you have to adjust this to your needs. Sorry, but can´t give you all the stuff you need, that will be beyond the frame.
You can try like this (I have not tested but hope it will work)
public class MainActivity extends BaseActivity {
private long remainingTimeForTimer = 0;
private CountDownTimer mCountDownTimer
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Start first timer
test1(120 * 1000);
// now on the basis of remaining timer you can cancel current timer and after that second timer you can start that timer with remaining time
if(remainingTimeForTimer > 0)
{
test1(remainingTimeForTimer);
}
}
private void test1(long totalTimerTime)
{
mCountDownTimer = new CountDownTimer(totalTimerTime, 1000) {
#Override
public void onTick(long millisUntilFinished) {
remainingTimeForTimer = millisUntilFinished;
}
#Override
public void onFinish() {
//trialCount = 0;
}
};
mCountDownTimer.start();
}
#Override
protected void onDestroy() {
if (mCountDownTimer != null) {
mCountDownTimer.cancel();
}
super.onDestroy();
}
}
Resolved
I have resolved this issue after trying multiple times. I ended up putting the larger timer in the onFinish of the shorter one and setting the initial time of that longer timer equal to millisUntilFinished. Then I cancel the long timer when the user presses enter and it automatically starts with the updated time whenever the EditText box is displayed.

Countdown timer which has increment/decrement option that can be set by user

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 :)

Categories