Restart countodown timer with different timer android - android

I am making a repeating countdown timer app.I require the countdown timer to restart with a different time.I am using a global variable in the constructor of the countdown timer.But the problem is that it always restarts from the starting of the first given interval.
public void chance(final int tota, final int cur, final int exercise,int pass,int flag)
{
Log.i("inside value","reached");
a = new CountDownTimer((tempmilliseconds) * 1000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
tempmilliseconds = (int) millisUntilFinished / 1000;
Log.i("inside value",Integer.toString(tempmilliseconds));
updatetimer(millisUntilFinished);
}
#Override
public void onFinish() {
mtext.setText("0:00");
cancel();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
currentcompleted++;
if (on == 0) {
on = 1;
int exercis = MainActivity.restmint * 60 + MainActivity.restsec;
tempmilliseconds=exercis;
chance(tota, curr + 1, exercis, 0, 0);
} else {
on = 0;
int exercis = MainActivity.exermint * 60 + MainActivity.exersec;
tempmilliseconds=exercis;
chance(tota, curr + 1, exercis, 0, 0);
}
}
}, 1000);
}
};
a.start();
}
Below is the code for resume operations:
public void resume(View view) {
Button mytext=(Button) findViewById(R.id.resume);
if( mytext.getText().toString()=="Pause") {
mytext.setText("Play");
a.cancel();
}
else {
mytext.setText("Pause");
Log.i("Value of temp",Integer.toString(tempmilliseconds));
a.start();
}
}
The timer is stopping but when started in the resume function restarts with the original time and not specified by tempmilliseconds.Note tempmilliseconds is updated every seconds.
Any help/snippets/suggestions is appreciated.Thank you!

A CountDownTimer will not allow itself to be disturbed in any case. It will remember the time it was born with till someone kills it.
If you look at its documentation you'd see that it directly inherits from Object class and has only four methods: start(), cancel(), onFinish() (abstract) and onTick() (abstract). Thats pretty much it. So, you basically are left with no choice but to call cancel() and then re-initialise the timer. Or, you can extend the CountDownTimer class and encapsulate this under the hood.
In either case the cost of cancelling ad re-initialising may get tedious.

Related

Android - TextView with dynamic text

For a simple Timer App I try to add a TextView to my app that says something like "15 seconds remaining", obviously this changes every seccond until it finally changes to "time up!". My idea was to use a loop like this:
while(now<endTime):
remaining=endTime-now;
text.setText(remaining);
While this could work, I am unsure if this is the right approach or if theres a better option.
You can use a handler to do it as below:
Handler myHandler=new Handler();
myHandler.postDelayed(timer, 1000);
private Runnable timer= new Runnable() {
public void run() {
if(counter==15){
textview.setText("Time Up");
counter=0;
}
else{
counter++;
textview.setText(counter+ " remaining");}
}
};
Use a CountDownTimer, instead.
I use this code snippet to achive a similar result:
final int secs = 5;
new CountDownTimer((secs +1) * 1000, 1000) // Wait 5 secs, tick every 1 sec
{
#Override
public final void onTick(final long millisUntilFinished)
{
txtCount.setText("" + (int) (millisUntilFinished * .001f));
}
#Override
public final void onFinish()
{
txtCount.setText("GO!");
}
}.start();
In the onFinish() handler you can do the "elapsed time" stuff

Keep Timer Ticking in Background

How can I keep the value of my timer resuming after going to another activity , my problem is that it's set to default if I switched to another activity I thought of using sharedpreference but it won't help because I need it to keep decrementing in the background.
public void reset()
{
countDownTimer.cancel();
}
private void setTimer() {
int time = 5;
if(countDownTimer==null)
{
totalTimeCountInMilliseconds = 60 * time * 1000;
}
else
{
reset();
totalTimeCountInMilliseconds = 60 * time * 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) {
seconds = leftTimeInMilliseconds / 1000;
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);
}
}.start();
}
You should stop your CountDownTimer in onPause and restart in onResume, your textViewShowTime might not be valid while your activity is in background.
If you need to call some code every 500ms no matter what activity you are in, then consider using AlarmManager.

Android countdown timer wont accept variable

i just started to learn creating android apps. I wanted to create a simple count down timer that takes a value from a edittext but countdown timer does not seem to run.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countDownTxt = (TextView) findViewById(R.id.countDownView);
intervalTxt = (TextView) findViewById(R.id.intervalText);
findViewById(R.id.startBN).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
int testInt = 30;
//countDownTxt.setText(intervalTxt.getText());
int interval = Integer.parseInt(intervalTxt.getText().toString());
Log.d("buttonpressed", "interval for countdown is " + interval);
cdt = new CountDownTimer(Integer.parseInt(intervalTxt.getText().toString()), 1000) {
public void onTick(long millisUntilFinished) {
Log.d("counttimer1", "haha1");
countDownTxt.setText(""+ millisUntilFinished / 1000);
}
public void onFinish() {
cancel();
}
}.start();
}
}
);
}
In particular, this program works only if i enter a numerical value such as 30000 in the 1st parameter of the CountDownTimer "cdt = new CountDownTimer(testInt, 1000)"
Can someone enlighten me please? Thank you!
"Doesn't work" how? You should post the error message you're getting or other symptoms of "doesn't work."
What's probably happening is CountDownTimer accepts only long values as the first parameter of its constructor. Not int values.
Change int testInt = 30 to long testLong = 10000.0f and see what happens.
The first parameter means milliseconds, by the way, so "30" isn't really going to get you much in the first place.
onTick() method is called in a separate Thread. But you don't have right to use setText() method outside the GUI Thread.
You must use a Handler object or Activity.postOnUiThread() method to execute something in the GUI Thread :
cdt = new CountDownTimer(Integer.parseInt(intervalTxt.getText().toString()), 1000) {
public void onTick(long millisUntilFinished) {
Log.d("counttimer1", "haha1");
runOnUiThread(new Runnable() {
#Override
public void run() {
countDownTxt.setText("" + millisUntilFinished / 1000);
}
});
countDownTxt.setText(""+ millisUntilFinished / 1000);
}
public void onFinish() {
cancel();
}
}.start();
For more informations, read http://developer.android.com/guide/components/processes-and-threads.html#Threads

CountDownTimer runs in old Activity when switching Activities

I have a CountDownTimer, which needs to run all the time. There are 2 Activities (A and B). Activity A has the CountDownTimer, which updates a TextView inside it. When I switch to B, the CountDownTimer still runs (it is the desired behavoir), but when I switch back to A, there seems to be an old and a new A. The timer does not update a TextView inside of the "new" A. It is started only once when A is first visited. Any ideas of how to solve this problem? Maybe put the timer somewhere else?
Edit: Some code:
private void prepareTimer() {
// TODO: DOES NOT WORK YET! (switching activities -> runs in old activity)
textTime = (TextView) findViewById(R.id.text_time); // is a field
if (!timerRunning) {
timerRunning = true;
int duration = 60000;
timer = new CountDownTimer(duration, 1000) {
public void onTick(long millisUntilFinished) {
long minsLeft = (long) Math.floor((double) millisUntilFinished / (double) Constants.ONE_MINUTE) + 1;
textTime.setText(minsLeft + " Min.");
}
public void onFinish() {
textTime.setText("done!");
}
};
timer.start();
}
}
CDT is running in its own separate thread. The TextView reference you are trying to access, in that CDT is no longer usable (because your activity A was no longer visible while you was in B) try to create new reference that TextView when you return to A. The CDT thread was still running regardless you have moved from A to B or viceversa. I hope this will help. Make sure you do changes in UI thread. ;)
Edit:
private void prepareTimer() {
// TODO: DOES NOT WORK YET! (switching activities -> runs in old activity)
textTime = (TextView) findViewById(R.id.text_time); // is a field
if (!timerRunning) {
timerRunning = true;
int duration = 60000;
timer = new CountDownTimer(duration, 1000) {
public void onTick(long millisUntilFinished) {
long minsLeft = (long) Math.floor((double) millisUntilFinished / (double) Constants.ONE_MINUTE) + 1;
textTime.setText(minsLeft + " Min.");
}
public void onFinish() {
textTime.setText("done!");
}
};
timer.start();
}
else
{
textTime = (TextView) findViewById(R.id.text_time);
}
}

Timer in Android not updating

I have a timer in android to countdown to a future date, but it is not refreshing. Any help appreciated. my code is posted below:
public class Activity1 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView t = (TextView)findViewById(R.id.countdown);
t.setText(timeDif());
I believe that t.setText just needs to be constantly updated, but am unsure of how to do that.
}
public String timeDif()
{
GregorianCalendar then = new GregorianCalendar(2012, 07, 21, 6, 0, 0);
Calendar now = Calendar.getInstance();
long arriveMilli = then.getTimeInMillis();
long nowMilli = now.getTimeInMillis();
long diff = arriveMilli - nowMilli;
int seconds = (int) (diff / 1000);
int minutes = seconds / 60;
seconds %= 60;
int hours = minutes / 60;
minutes %= 60;
int days = hours / 24;
hours %= 24;
String time = days + ":" +zero(hours)+":"+zero(minutes)+":"+zero(seconds);
return time;
}
private int zero(int hours) {
// TODO Auto-generated method stub
return 0;
}
}
The textbox wont update unless you do it in its own thread. The Timer runs on a different thread than the UI. Here is how I did it.
myTimer = new Timer();
myTimerTask = new TimerTask() {
#Override
public void run() {
TimerMethod();
}
};
myTimer.schedule(myTimerTask, 0, 100);
private void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
if (isPaused != true) {
this.tmrMilliSeconds--;
this.runOnUiThread(Timer_Tick);
}
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
if (tmrSeconds > 0) {
if (tmrMilliSeconds <= 0) {
tmrSeconds--;
tmrMilliSeconds = 9;
}
} else {
Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(1000);
myTimer.cancel();
tmrSeconds = setTime;
tmrMilliSeconds = 0;
isPaused = true;
}
//Do something to the UI thread here
timerText.setText(String.format("%03d.%d", tmrSeconds, tmrMilliSeconds));
}
};
That is part of the code for a count down clock I made for an ap. It demonstrates how to have one thread run (The public void run()) part, and then another part that runs on the UI thread. Hope that helps.
You shouldn't be doing this with a timer. A timer uses a thread and you don't need one (and it complicates things unnecessarily). You need to use a Runable and Handler's postDelayed method to do it. It is easier and lighter weight.
Handler mHandler = new Handler();
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
//update here
mHandler.postDelayed(mUpdateTimeTask, 100);
}
};
private void startTimer()
{
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
}

Categories

Resources