2013-05-02 53 views
0

我需要每5秒鐘使用Mono for Android運行一個方法。 Android中有計劃的計時器嗎?我曾嘗試這個代碼,但是,它無法啓動:Android預定定時器 - 適用於Android或Java的單聲道

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(); 
    } 
} 

}

回答

0

爲什麼不直接使用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秒:

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)); 
     } 
    }); 
+0

(可選)將Date參數設置爲0或新的Date()將在ScheduleAtFixedRate中工作。 – 2013-05-03 15:19:35

3

我有同樣的問題,我有一段時間後啓動服務。

 DateTime dt = DateTime.Now; 
     t1 = new System.Timers.Timer(200); 
     t1.Elapsed += new ElapsedEventHandler(OnTimeEvent); 
     t1.Interval = 4000; 
     t1.Enabled = true; 
     t1.Start(); 
    } 
    private void OnTimeEvent(object source, ElapsedEventArgs e) 
    { 
     RunOnUiThread(delegate 
     { 
     //this is my service which i was starting at every 4 seconds 
      StartService(new Intent(this, typeof(ServiceClass))); 
     }); 
    }