I’m making a System.Timer, using the elapse event to update a int of a object, like this:
public class VariaveisGlobais : Java.Lang.Object
{
SqlConnection BDLinha1 = new SqlConnection();
public SqlConnection p_BDLinha1
{
get { return BDLinha1; }
set { BDLinha1 = value; }
}
System.Timers.Timer Temporizador = new System.Timers.Timer(1000);
public System.Timers.Timer p_Temporizador
{
get { return Temporizador; }
set { Temporizador = value; }
}
int Tempo = 0;
public int p_Tempo
{
get { return Tempo; }
set { Tempo = value; }
}
}
Then i use a delegate to update the var tempo:
Vars.p_Temporizador.Elapsed += delegate
{
RunOnUiThread(() => AutoCompleta4.Text = Vars.p_Tempo.ToString());
Vars.p_Tempo++;
};
And to handle the screen rotation i use:
public override Java.Lang.Object OnRetainNonConfigurationInstance()
{
return Vars;
}
And use LastNonConfigurationInstance to restore the variables of my application.
But, every time i rotate the screen, the timer add one more number to the event. Example:
1 rotation = 1 – 3 – 5 – 7 …, 2 rotations = 1 – 4 – 7 …, 3 rotations = 1 – 5 – 9 – 13 …
Looks like every time i rotate the screen, the event isn’t destroyed with the activity, and one more is build.
Any sugestions ?
Tks.
If by “event” you mean the
Vars.p_Temporizador.Elapsedevent, then no, events are not automatically cleared unless you explicitly do so. The result, then, is that on every screen rotation you’ll be adding a new event handler, all of the event handlers will fire, and (worst) the “dead” activities won’t be collectable (because there’ll be an event handler keeping the Activity alive).I think the easiest fix would be to not subscribe to the event from
OnCreate()(which is where I assume you’re subscribing to the event), and instead use a field:This way, each time the Activity is recreated, you don’t need to worry about invalidating the event, you just need to update the VariaveisGlobais.activity1 field to reference the current Activity.
You may also want to override Activity.OnDestroy() to clear out the VariaveisGlobais.activity1 field: