Use System.Timers.Timer ??

haya5fhaya5f Baris KomurcuTRMember
edited February 2013 in Android

Hi .

After 3 seconds the textview text you want to exchange the project. code does not work. Where's the error I'm doing?

using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace AndroidApplication2
{
    [Activity(Label = "AndroidApplication2", MainLauncher = true, Icon = "@drawable/icon")]
    public class Activity1 : Activity
    {
        int count = 1;
        System.Timers.Timer t;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.MyButton);

            button.Click += delegate
            {
                t = new System.Timers.Timer();
                t.Interval = 3000;
                t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
                t.Start();
            };
        }

        protected void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            t.Stop();
            TextView v = (TextView)FindViewById(Resource.Id.textView1);
            v.Text = "ege";
        }
    }
}

Posts

  • haya5fhaya5f Baris Komurcu TRMember

    v.Text = "ege"; -- freezes on this line

  • JonathanPryorJonathanPryor Jonathan Pryor USModerator, Xamarin Team Xamurai

    The problem is that you're modifying a UI-bound object from a non-UI thread.

    From the System.Timers.Timer documentation:

    The server-based Timer is designed for use with worker threads in a multithreaded environment. Server timers can move among threads to handle the raised Elapsed event...

    t_Elapsed() will not be executed from the UI thread, which means it is not safe for it to call FindViewById(), or touch v, or do anything else on this, for that matter, except RunOnUiThread().

  • haya5fhaya5f Baris Komurcu TRMember

    Thank you very much :)

  • Jalexkoop21Jalexkoop21 Alexander Koop COMember

    Hi, I want that my application to close at 2 minutes. But when you restart activity change over time. How I can spend time from one activity to another?

  • SheepssjSheepssj Thiago Sabin BRMember

    I didnt udnerstand you Jalex but probably this will help. You can in some class in your app create a public static Timer yourTimer; And then you can reach it from anywhere in your application with

    yourClassName.yourTimer

    Or explain better what you want

  • dana_Soranidana_Sorani dana sorani IQMember

    thanks code work for me :)

Sign In or Register to comment.