I'm making an Android application on Xamarin and I want this code to be looped over and over. But when it's looping it shows literally nothing
public MainPage()
{
InitializeComponent();
for (int i = 0; i < 100; i )
{
Thread.Sleep(2000);
string app = "notepad";
HttpClient httpClient = new HttpClient();
var result = httpClient.GetAsync("LINK/ob/ob.php?text=" app).Result;
var contents = result.Content.ReadAsStringAsync().Result;
string decider = contents.ToString();
if (decider.Length > 7)
{
van.Text = "The " app " is ON";
van.TextColor = Xamarin.Forms.Color.Green;
}
else
{
van.Text = "The " app " is off";
}
}
}
CodePudding user response:
first, don't do this in the constructor. Doing so guarantees that your page won't display until the code completes
second, instead of doing this in a loop with Thread.Sleep()
use a timer instead
Timer timer;
int counter;
protected override void OnAppearing()
{
timer = new Timer(2000);
timer.Elapsed = OnTimerElapsed;
timer.Enabled = true;
}
private void OnTimerElapsed(object sender, ElapsedEventArgs a)
{
counter ;
if (counter > 100) timer.Stop();
// put your http request code here
// only the UI code updates should run on the main thread
MainThread.BeginInvokeOnMainThread(() =>
{
if (decider.Length > 7)
{
van.Text = "The " app " is ON";
van.TextColor = Xamarin.Forms.Color.Green;
}
else
{
van.Text = "The " app " is off";
}
});
}