Android 计划计时器

编程入门 行业动态 更新时间:2024-10-17 04:58:24
本文介绍了Android 计划计时器 - 适用于 Android 或 Java 的 Mono的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我需要使用 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-24 17:52:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1068470.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:计时器   计划   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!