I have this code in a BroadcastReceiver that should change a textview with the word "CHARGING" if the phone is plugged or with a Count Down Timer if it is not:
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
TextView textView2 = (TextView) findViewById(R.id.textView2);
TextView textView3 = (TextView) findViewById(R.id.textView3);
String str = Boolean.toString(isCharging);
textView2.setText(str);
CountDownTimer aCounter = new CountDownTimer((long) timeleft, 1000) {
public void onTick(long millisUntilFinished) {
long seconds = millisUntilFinished / 1000;
mTextField.setText(String.format("%02d:%02d:%02d", seconds / 3600,
(seconds % 3600) / 60, (seconds % 60)));
}
public void onFinish() {
mTextField.setText("done!");
}
};
if (usbCharge || acCharge ) {
textView3.setText("Charging");
mTextField.setText("CHARGING");
aCounter.cancel();
aCounter = null;
}
else {
textView3.setText("Not Charging");
mTextField.setText("NOT CHARGING");
aCounter.start();
}
}
My problem is if I start the app with the phone plugged I can see the word "CHARGING" in the textview, when I unplug the phone I can see the count down timer, but when I plug the phone again, I only see the word "Charging" a millisecond and then I see the count down timer again. And if I unplug the phone again, I see two count down timers at the same time in the same textview.
It is like I create a new count down timer every time I plug the phone without destroy the previous one.
Oh ok, first of all, don't make CountDownTimer class like that
/* Declare a class level object */
private MyCountDownTimer myCountDownTimer;
private class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long millisInFuture,
long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#Override
public void onTick(long millisUntilFinished) {
//TODO some code here
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
}
}
then when you want to start countdown timer
myCountDownTimer = new MyCountDownTimer(
999999999999999999L, 15 * 1000);
myCountDownTimer.start();
and when you want to cancel that
if(myCountDownTimer!=null)
{
myCountDownTimer.cancel();
}
Related
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();
}
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.
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();
}
}
It was working fine when it was just one timer but when I added inserted a switch and added two more timers, the stop timer button seized working. All the code is pasted below:
public class timer extends Activity implements OnClickListener {
private Button buttonStartTime, buttonStopTime, buttonStartTime2, buttonStopTime2, buttonStartTime3, buttonStopTime3;
private EditText edtTimerValue, edtTimerValue2, edtTimerValue3;
private TextView textViewShowTime, textViewShowTime2, textViewShowTime3; // will show the time
private CountDownTimer countDownTimer, countDownTimer2, countDownTimer3; // built in android class
// CountDownTimer
private long totalTimeCountInMilliseconds, totalTimeCountInMilliseconds2, totalTimeCountInMilliseconds3; // total count down time in
// milliseconds
private long timeBlinkInMilliseconds, timeBlinkInMilliseconds2, timeBlinkInMilliseconds3; // start time of start blinking
private boolean blink, blink2, blink3; // controls the blinking .. on and off
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
buttonStartTime = (Button) findViewById(R.id.btnStartTime);
buttonStopTime = (Button) findViewById(R.id.btnStopTime);
textViewShowTime = (TextView) findViewById(R.id.tvTimeCount);
edtTimerValue = (EditText) findViewById(R.id.edtTimerValue);
buttonStartTime2 = (Button) findViewById(R.id.btnStartTime2);
buttonStopTime2 = (Button) findViewById(R.id.btnStopTime2);
textViewShowTime2 = (TextView) findViewById(R.id.tvTimeCount2);
edtTimerValue2 = (EditText) findViewById(R.id.edtTimerValue2);
buttonStartTime3 = (Button) findViewById(R.id.btnStartTime3);
buttonStopTime3 = (Button) findViewById(R.id.btnStopTime3);
textViewShowTime3 = (TextView) findViewById(R.id.tvTimeCount3);
edtTimerValue3 = (EditText) findViewById(R.id.edtTimerValue3);
buttonStartTime.setOnClickListener(this);
buttonStopTime.setOnClickListener(this);
buttonStartTime2.setOnClickListener(this);
buttonStopTime2.setOnClickListener(this);
buttonStartTime3.setOnClickListener(this);
buttonStopTime3.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStartTime:
if (v.getId() == R.id.btnStartTime) {
textViewShowTime.setTextAppearance(getApplicationContext(),
R.style.normalText);
setTimer();
buttonStopTime.setVisibility(View.VISIBLE);
buttonStartTime.setVisibility(View.GONE);
edtTimerValue.setVisibility(View.GONE);
edtTimerValue.setText("");
startTimer();
} else if (v.getId() == R.id.btnStopTime) {
countDownTimer.cancel();
buttonStartTime.setVisibility(View.VISIBLE);
buttonStopTime.setVisibility(View.GONE);
edtTimerValue.setVisibility(View.VISIBLE);
}
break;
case R.id.btnStartTime2:
if (v.getId() == R.id.btnStartTime2) {
textViewShowTime2.setTextAppearance(getApplicationContext(),
R.style.normalText);
setTimer2();
buttonStopTime2.setVisibility(View.VISIBLE);
buttonStartTime2.setVisibility(View.GONE);
edtTimerValue2.setVisibility(View.GONE);
edtTimerValue2.setText("");
startTimer2();
} else if (v.getId() == R.id.btnStopTime2) {
countDownTimer2.cancel();
buttonStartTime2.setVisibility(View.VISIBLE);
buttonStopTime2.setVisibility(View.GONE);
edtTimerValue2.setVisibility(View.VISIBLE);
}
break;
case R.id.btnStartTime3:
if (v.getId() == R.id.btnStartTime3) {
textViewShowTime3.setTextAppearance(getApplicationContext(),
R.style.normalText);
setTimer3();
buttonStopTime3.setVisibility(View.VISIBLE);
buttonStartTime3.setVisibility(View.GONE);
edtTimerValue3.setVisibility(View.GONE);
edtTimerValue3.setText("");
startTimer3();
} else if (v.getId() == R.id.btnStopTime) {
countDownTimer3.cancel();
buttonStartTime3.setVisibility(View.VISIBLE);
buttonStopTime3.setVisibility(View.GONE);
edtTimerValue3.setVisibility(View.VISIBLE);
}
break;
}
}
private void setTimer() {
int time = 0;
if (!edtTimerValue.getText().toString().equals("")) {
time = Integer.parseInt(edtTimerValue.getText().toString());
} else
Toast.makeText(timer.this, "Please Enter Minutes...",
Toast.LENGTH_LONG).show();
totalTimeCountInMilliseconds = 60 * time * 1000;
timeBlinkInMilliseconds = 30 * 1000;
}
private void startTimer() {
countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {
// 500 means, onTick function will be called at every 500
// milliseconds
#Override
public void onTick(long leftTimeInMilliseconds) {
long seconds = leftTimeInMilliseconds / 1000;
if (leftTimeInMilliseconds < timeBlinkInMilliseconds) {
textViewShowTime.setTextAppearance(getApplicationContext(),
R.style.blinkText);
// change the style of the textview .. giving a red
// alert style
if (blink) {
textViewShowTime.setVisibility(View.VISIBLE);
// if blink is true, textview will be visible
} else {
textViewShowTime.setVisibility(View.INVISIBLE);
}
blink = !blink; // toggle the value of blink
}
textViewShowTime.setText(String.format("%02d", seconds / 60)
+ ":" + String.format("%02d", seconds % 60));
// format the textview to show the easily readable format
}
#Override
public void onFinish() {
// this function will be called when the timecount is finished
textViewShowTime.setText("Time up!");
textViewShowTime.setVisibility(View.VISIBLE);
buttonStartTime.setVisibility(View.VISIBLE);
buttonStopTime.setVisibility(View.GONE);
edtTimerValue.setVisibility(View.VISIBLE);
}
}.start();
}
private void setTimer2() {
int time = 0;
if (!edtTimerValue2.getText().toString().equals("")) {
time = Integer.parseInt(edtTimerValue2.getText().toString());
} else
Toast.makeText(timer.this, "Please Enter Minutes...",
Toast.LENGTH_LONG).show();
totalTimeCountInMilliseconds2 = 60 * time * 1000;
timeBlinkInMilliseconds2 = 30 * 1000;
}
private void startTimer2() {
countDownTimer2 = new CountDownTimer(totalTimeCountInMilliseconds2, 500) {
// 500 means, onTick function will be called at every 500
// milliseconds
#Override
public void onTick(long leftTimeInMilliseconds) {
long seconds = leftTimeInMilliseconds / 1000;
if (leftTimeInMilliseconds < timeBlinkInMilliseconds2) {
textViewShowTime2.setTextAppearance(getApplicationContext(),
R.style.blinkText);
// change the style of the textview .. giving a red
// alert style
if (blink2) {
textViewShowTime2.setVisibility(View.VISIBLE);
// if blink is true, textview will be visible
} else {
textViewShowTime2.setVisibility(View.INVISIBLE);
}
blink2 = !blink; // toggle the value of blink
}
textViewShowTime2.setText(String.format("%02d", seconds / 60)
+ ":" + String.format("%02d", seconds % 60));
// format the textview to show the easily readable format
}
#Override
public void onFinish() {
// this function will be called when the timecount is finished
textViewShowTime2.setText("Time up!");
textViewShowTime2.setVisibility(View.VISIBLE);
buttonStartTime2.setVisibility(View.VISIBLE);
buttonStopTime2.setVisibility(View.GONE);
edtTimerValue2.setVisibility(View.VISIBLE);
}
}.start();
}
private void setTimer3() {
int time = 0;
if (!edtTimerValue3.getText().toString().equals("")) {
time = Integer.parseInt(edtTimerValue3.getText().toString());
} else
Toast.makeText(timer.this, "Please Enter Minutes...",
Toast.LENGTH_LONG).show();
totalTimeCountInMilliseconds3 = 60 * time * 1000;
timeBlinkInMilliseconds3 = 30 * 1000;
}
private void startTimer3() {
countDownTimer3 = new CountDownTimer(totalTimeCountInMilliseconds3, 500) {
// 500 means, onTick function will be called at every 500
// milliseconds
#Override
public void onTick(long leftTimeInMilliseconds3) {
long seconds = leftTimeInMilliseconds3 / 1000;
if (leftTimeInMilliseconds3 < timeBlinkInMilliseconds3) {
textViewShowTime3.setTextAppearance(getApplicationContext(),
R.style.blinkText);
// change the style of the textview .. giving a red
// alert style
if (blink3) {
textViewShowTime3.setVisibility(View.VISIBLE);
// if blink is true, textview will be visible
} else {
textViewShowTime3.setVisibility(View.INVISIBLE);
}
blink3 = !blink; // toggle the value of blink
}
textViewShowTime3.setText(String.format("%02d", seconds / 60)
+ ":" + String.format("%02d", seconds % 60));
// format the textview to show the easily readable format
}
#Override
public void onFinish() {
// this function will be called when the timecount is finished
textViewShowTime3.setText("Time up!");
textViewShowTime3.setVisibility(View.VISIBLE);
buttonStartTime3.setVisibility(View.VISIBLE);
buttonStopTime3.setVisibility(View.GONE);
edtTimerValue3.setVisibility(View.VISIBLE);
}
}.start();
}
}
You need to switch on stopping buttons as well.
switch (v.getId()) {
case R.id.btnStartTime:
means v.getId() == R.id.btnStartTime inside this case so checking the value of v.getId() there is useless. The first if (v.getId() == R.id.btnStartTime) will always be true, the second one (v.getId() == R.id.btnStopTime) always false.
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 :)