I want to create a timer thread for android with Xamarin

How to run this code at 1 second intervals or in a “While (True)” loop with a 1 second sleep code for a thread?

private void GetCodeOnServer()
{

     WebClient _client = new WebClient();

     string _code = _client.DownloadString(new Uri(@"http://myUrl/car"));

     Toast.MakeText(this, "Code: " + _code, ToastLength.Long).Show();


}
+4
source share
2 answers

You will not be able to call the Internet on the main topic of Activity. Use Async to execute code. The Async task runs in the background, and Toast will display for you when you download the content. The example below will help.

private class GetStringTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String str = "...";
            /** String From Web **/
            return str;
        }

        @Override
        protected void onPostExecute(String address) {
            // Show Toast Here
        }
    }
0
source

If you need to do something with an interval of 1 second, you can use a timer for this. I used this code in Xamarin.Android:

   private void CountDown ()
    {

        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Interval = 1000; 
        timer.Elapsed += OnTimedEvent;
        timer.Enabled = true;


    }

    private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
    {

    }

OnTimedEvent , async Task.

+11

All Articles