I’ve created a small app with a countdown timer for poker blind, but I’ve noticed that when the lockscreen is on, the timer will reset from start.
How can I resolve this?
This is the code of the class:
public class timer extends Activity {
/** Called when the activity is first created. */
TextView contoallarovescia;
TextView clicca;
public boolean touchattivo=false;
public int giro=1;
public int girosecondi=8*60;
@Override
public void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.timer);
contoallarovescia = (TextView) this.findViewById(R.id.contoallarovescia);
Typeface typeFace=Typeface.createFromAsset(getAssets(),"font/LCDMB___.TTF");
contoallarovescia.setTypeface(typeFace);
clicca = (TextView) this.findViewById(R.id.clicca);
chiamatimer(girosecondi*1000,1000);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// MotionEvent object holds X-Y values
if (touchattivo)
{
chiamatimer(girosecondi*1000,1000);
}
return super.onTouchEvent(event);
}
public void chiamatimer(int secondi, int ciclo)
{
touchattivo=false;
clicca.setVisibility(View.INVISIBLE);
new CountDownTimer(secondi, ciclo) {
public void onTick(long millisUntilFinished) {
int sec =(int) (millisUntilFinished / 1000);
String result = String.format("%02d:%02d", sec / 60, sec % 60);
contoallarovescia.setText(result);
}
public void onFinish() {
String result = String.format("%02d:%02d", 0, 0);
giro++;
if (giro==5)
{
girosecondi=6*60;
}
contoallarovescia.setText(result);
clicca.setVisibility(View.VISIBLE);
touchattivo=true;
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {}
}
}.start();
}
}
Tnx!
You need to look at application life cycle in the android documents – in the case you suggest I would imagine that your application is simply being shut-down and restarted by android – thus your onCreate gets called again and the timer is reset.
Android applications are not simple objects and part of what you have to cope with is the opsys shoving you around when needed.
Specifically take a look at onPause and how you might store your end time in the bundle that is later passed to your onCreate. This will solve your current bug.