将计时器添加到Xamarin应用程序(c#)

时间:2017-12-18 20:16:52

标签: c# android xamarin timer

所以我需要一个计时器从60秒倒计时。我是Xamarin的新手,不知道它接受了什么。有关如何开始的任何建议吗?

它将在android中使用

你可以使用System.Timers.Timer吗?

4 个答案:

答案 0 :(得分:1)

您可以使用System.Threading.Timer类,该类在Xamarin文档中有记录:https://developer.xamarin.com/api/type/System.Threading.Timer/

或者,对于Xamarin.Forms,您可以通过Device类访问跨平台的Timer:

DefinePlugin

答案 1 :(得分:0)

如果您只需要Android,可以使用

System.Threading.Timer

在使用Xamarin Forms的共享代码中,您可以使用

Device.StartTimer(...)

或者您可以使用以下高级功能实现一个yourselfe:

public sealed class Timer : CancellationTokenSource {
    private readonly Action _callback;
    private int _millisecondsDueTime;
    private readonly int _millisecondsPeriod;

    public Timer(Action callback, int millisecondsDueTime) {
        _callback = callback;
        _millisecondsDueTime = millisecondsDueTime;
        _millisecondsPeriod = -1;
        Start();
    }

    public Timer(Action callback, int millisecondsDueTime, int millisecondsPeriod) {
        _callback = callback;
        _millisecondsDueTime = millisecondsDueTime;
        _millisecondsPeriod = millisecondsPeriod;
        Start();
    }

    private void Start() {
        Task.Run(() => {
            if (_millisecondsDueTime <= 0) {
                _millisecondsDueTime = 1;
            }
            Task.Delay(_millisecondsDueTime, Token).Wait();
            while (!IsCancellationRequested) {

                //TODO handle Errors - Actually the Callback should handle the Error but if not we could do it for the callback here
                _callback();

                if(_millisecondsPeriod <= 0) break;

                if (_millisecondsPeriod > 0 && !IsCancellationRequested) {
                    Task.Delay(_millisecondsPeriod, Token).Wait();
                }
            }
        });
    }

    public void Stop() {
        Cancel();
    }

    protected override void Dispose(bool disposing) {
        if (disposing) {
            Cancel();
        }
        base.Dispose(disposing);
    }

}

答案 2 :(得分:0)

您可以随时使用

Task.Factory.StartNewTaskContinuously(YourMethod, new CancellationToken(), TimeSpan.FromMinutes(10));

请务必将以下类添加到项目中

static class Extensions
{
    /// <summary>
    /// Start a new task that will run continuously for a given amount of time.
    /// </summary>
    /// <param name="taskFactory">Provides access to factory methods for creating System.Threading.Tasks.Task and System.Threading.Tasks.Task`1 instances.</param>
    /// <param name="action">The action delegate to execute asynchronously.</param>
    /// <param name="cancellationToken">The System.Threading.Tasks.TaskFactory.CancellationToken that will be assigned to the new task.</param>
    /// <param name="timeSpan">The interval between invocations of the callback.</param>
    /// <returns>The started System.Threading.Tasks.Task.</returns>
    public static Task StartNewTaskContinuously(this TaskFactory taskFactory, Action action, CancellationToken cancellationToken, TimeSpan timeSpan
        , string taskName = "")
    {
        return taskFactory.StartNew(async () =>
        {
            if (!string.IsNullOrEmpty(taskName))
            {
                Debug.WriteLine("Started task " + taskName);
            }
            while (!cancellationToken.IsCancellationRequested)
            {
                action();
                try
                {
                    await Task.Delay(timeSpan, cancellationToken);
                }
                catch (Exception e)
                {
                    break;
                }
            }
            if (!string.IsNullOrEmpty(taskName))
            {
                Debug.WriteLine("Finished task " + taskName);
            }
        });
    }
}

答案 3 :(得分:0)

是的,您可以使用System.Timers.Timer

在Android中,我们可以像这样使用java.util.Timer

    private int i;

    final Timer timer=new Timer();
    TimerTask task=new TimerTask() {
        @Override
        public void run() {
            if (i < 60) {
                i++;
            } else {
                timer.cancel();
            }
            Log.e("time=",i+"");
        }
    };
    timer.schedule(task, 0,1000);

在Xamarin.Android中,我们也可以像这样使用java.util.Timer

[Activity(Label = "Tim", MainLauncher = true)]
public class MainActivity : Activity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        Timer timer = new Timer();
        timer.Schedule(new MyTask(timer),0,1000);
    }
}

class MyTask : TimerTask
{
    Timer mTimer;
    public MyTask(Timer timer) {
        this.mTimer = timer;
    }
    int i;
    public override void Run()
    {
        if (i < 60)
        {
            i++;
        }
        else {
            mTimer.Cancel();
        }

        Android.Util.Log.Error("time",i+"");
    }
}