Hey there!
I'm new in developing Android apps using Xamarin, so here's my question. My timer is not working, where is the problem?
public class MainActivity : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.SplashScreen); ActionBar.Hide(); System.Timers.Timer Timer1 = new System.Timers.Timer(); Timer1.Interval = 3000; Timer1.Enabled = true; Timer1.Elapsed += (object sender, System.Timers.ElapsedEventArgs e) => { Timer1.Stop(); SetContentView(Resource.Layout.MainMenu); }; Timer1.Start(); } }
what you are looking for is the following:
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.SplashScreen); ActionBar.Hide(); System.Timers.Timer Timer1 = new System.Timers.Timer(); Timer1.Start(); Timer1.Interval = 3000; Timer1.Enabled = true; //Timer1.Elapsed += OnTimedEvent; Timer1.Elapsed += (object sender, System.Timers.ElapsedEventArgs e) => { Timer1.Stop(); RunOnUiThread(() => { SetContentView(Resource.Layout.Main); }); //Delete time since it will no longer be used. Timer1.Dispose(); }; Timer1.Start(); }
RunOnUIThread is what you need to be able to SetContentView.
Answers
what you are looking for is the following:
RunOnUIThread is what you need to be able to SetContentView.
why is the timer started twice?
may i ask something? what if i create an endless timer in OnCreate that runs a code every hour and the app is pause for 5 hours. when OnResume is called, it will continue its work or should i restart it on resume?
From microsoft official page, it says that timer ignores exceptions and continue its work, except if it is called with async.
System.Timers.Timer continue running even your app is on background.