我正在 Xamarin 上制作一個 Android 應用程式,我希望這段代碼可以一遍又一遍地回圈。但是當它回圈時,它實際上什么也沒顯示
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";
}
}
}
uj5u.com熱心網友回復:
首先,不要在建構式中這樣做。這樣做可以保證您的頁面在代碼完成之前不會顯示
其次,不要在回圈中這樣做,而是Thread.Sleep()
使用計時器
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";
}
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/470471.html
標籤:C# 安卓 xamarin xamarin.forms xamarin.android