Reputation: 1
I've created a countdowntimer that works but it starts again on each activity. I'm trying to save the countdown value and use it in the second activity. Below is the countdown code on my main activity page.
//Countdown Start
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
final int j = (int) millisUntilFinished / 1000;
long timed;
timed = millisUntilFinished;
TextView textic = (TextView) findViewById(R.id.textView2);
textic.setText("" + (millisUntilFinished));
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView textic = (TextView) findViewById(R.id.textView2);
textic.setText(Integer.toString((j)));;
}
});
}
public void onFinish() {
}
}.start();
//Countdown Finish
I've tried storing the countdown value and then using passextra in my intent to pass "timed" but that didn't work. I've searched around and can't find any solution that works. Any help would be greatly appreciated.
Thanks
================
EDIT
================
public class MainActivity extends startscreen{
private CountDownTimer timer3;
public void onCreate(){
timer3 = new CountDownTimer(10000,100){
public void onTick(long millisUntilFinished) {
TextView displaytime = (TextView) findViewById(R.id.textView3);
displaytime.setText("" + (millisUntilFinished));}
public void onFinish() {
}
}.start();
};;
public void startTimer(){
}
public void cancelTimer(){
}
==============
//Counter 1
Counter1 = new CountDownTimer(10000 , 1000) {
public void onTick(long millisUntilFinished) {
mCounter1TextField.setText("Seconds left: " + formatTime(millisUntilFinished));
}
public void onFinish() {
mCounter1TextField.setText("Finished!");
// Counter1.start();
}
};
Counter1.start();
public void starttimer() {
Counter1.start();
}
And then in my second activity i've got:
MainActivity Counter1 = (MainActivity) getApplicationContext();
Counter1.starttimer();
TextView mCounter1TextField=(TextView)findViewById(R.id.textView4);
mCounter1TextField.setText("Seconds left: " + (Counter1));
Upvotes: 0
Views: 1501
Reputation: 925
Extend the Application class and add your global timer there. Your class would look something like this
public class MyApplication extends Application{
private CountDownTimer timer;
public void onCreate(){
super.onCreate();
timer = new CountDownTimer(10000,100){
.....
};
}
public void startTimer(){
...
}
public void cancelTimer(){
...
}
}
Start this timer by making a call to getApplicationContext() from an activity
MyApplication application = (MyApplication) getApplicationContext();
application.startTimer();
Also, make sure you rename your application in your Android manifest.
<application ... android:name=".MyApplication" .../>
Upvotes: 1
Reputation: 1141
I would suggest either writing the CountDownTimer
in its own class and extend it as a Service
and then start the service when you want to start the timer, or make it a Singleton so all activities access the same timer.
Upvotes: 0