Android 计划计时器 - 适用于 Android 或 Java 的 Mono [英] Android Scheduled Timer - Mono for Android or Java

查看:32
本文介绍了Android 计划计时器 - 适用于 Android 或 Java 的 Mono的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 Mono for Android 每 5 秒运行一次方法.Android 中是否有预定的计时器?我试过这段代码,但是,它无法启动:

I need to run a method every 5 seconds using Mono for Android. Is there a scheduled timer in Android? I have tried this code, however, it fails to start:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Glass.Core.Interfaces;
using Glass.Core;
using Java.Util;

namespace Glass.UI.AN
{
[Application(Label = "Glass", Icon = "@drawable/icon")]
public class GlassApplication : Application
{
    Context context;

    public GlassApplication (IntPtr handle, JniHandleOwnership transfer)
        : base(handle, transfer)
    {
        this.context = BaseContext;
    }

    public override void OnCreate ()
    {
        base.OnCreate ();
        Timer timer = new Timer ();
        timer.ScheduleAtFixedRate (new CustomTimerTask(context), new Date(DateTime.Now.Year, DateTime.Now.Month, 
        DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute), 5000);
    }
}

public class CustomTimerTask: TimerTask
{
    Context context;

    public CustomTimerTask(Context context)
    {
        this.context = context;
    }

    public override void Run ()
    {
        GlassWebServiceProvider p = new GlassWebServiceProvider (context);
        p.SendCardReaders ();
    }
}

}

推荐答案

为什么不直接使用 System.Timers.Timer?

var timer = new Timer();
//What to do when the time elapses
timer.Elapsed += (sender, args) => FireTheMissiles();
//How often (5 sec)
timer.Interval = 5000;
//Start it!
timer.Enabled = true;

private void FireTheMissiles()
{
    //But I'm le tired...
}

另一种制作新TaskThread并让它每次休眠5秒的方法:

Another approach to make a new Task or Thread and let it sleep for 5 seconds every time:

Task.Factory.StartNew(() =>
    {
        while (true)
        {
            // do some stuff
            Thread.Sleep(TimeSpan.FromSeconds(5));
        }
    });

ThreadPool.QueueUserWorkItem(thread =>
    {
        while (true)
        {
            // do some stuff
            Thread.Sleep(TimeSpan.FromSeconds(5));
        }
    });

这篇关于Android 计划计时器 - 适用于 Android 或 Java 的 Mono的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆