c#→Android (Xamarin) ->每5分钟在后台启动一次任务

本文关键字:启动 后台 任务 一次 Android Xamarin 5分钟 | 更新日期: 2023-09-27 18:05:31

我想每5分钟运行一个任务。我试图解决它与IntentService和AlarmManager,我的代码:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.Main);
    var tkrServiceIntent = new Intent(this, typeof(GpsDataHandler));
    var tkrServicePendingIntent = PendingIntent.GetService(this, 0, tkrServiceIntent, 0);
    long interval = 5000;
    var firstStart = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) + 1000;
    var am = (AlarmManager)GetSystemService(Context.AlarmService);
    am.SetInexactRepeating(AlarmType.RtcWakeup, firstStart, interval, tkrServicePendingIntent);
    Toast.MakeText(this, "Service started", ToastLength.Long).Show();
}

我收到toast,表示服务已经启动,但是如果我查看正在运行的服务,我的应用程序没有服务。你能告诉我问题出在哪里吗?

c#→Android (Xamarin) ->每5分钟在后台启动一次任务

IntentService在一个运行在app后台的"activity"(如果我们可以调用它的话)中,所以最后它会调用OnDestroy() ..您可以使用计时器来解决您的问题,如:

using System;
using System.Threading;
class TimerExampleState {
    public int counter = 0;
    public Timer tmr;
}
class App {
   public static void Main() {
    TimerExampleState s = new TimerExampleState();
    // Create the delegate that invokes methods for the timer.
    TimerCallback timerDelegate = new TimerCallback(CheckStatus);
    // Create a timer that waits one second, then invokes every second.
    Timer timer = new Timer(timerDelegate, s, 1000, 1000);
    // Keep a handle to the timer, so it can be disposed.
    s.tmr = timer;
    // The main thread does nothing until the timer is disposed.
    while (s.tmr != null)
        Thread.Sleep(0);
    Console.WriteLine("Timer example done.");
   }
   // The following method is called by the timer's delegate.
   static void CheckStatus(Object state) {
    TimerExampleState s = (TimerExampleState) state;
    s.counter++;
          Console.WriteLine("{0} Checking Status {1}.",DateTime.Now.TimeOfDay, s.counter);
        if (s.counter == 5) {
        // Shorten the period. Wait 10 seconds to restart the timer.
        (s.tmr).Change(10000,100);
        Console.WriteLine("changed...");
    }
        if (s.counter == 10) {
        Console.WriteLine("disposing of timer...");
        s.tmr.Dispose();
        s.tmr = null;
    }
   }
}

来源:https://developer.xamarin.com/api/type/System.Threading.Timer/

希望这段代码对你有所帮助:-

async void StartTimer()
{
   await Task.Delay(60000); //60 seconds
   // Do your code
   StartTimer(); // Again Call 
}

调用"StartTimer()"方法在你想要的地方。只呼叫一次,然后在60秒后自动呼叫。

谢谢! !

您可以使用xamarin forms设备类创建自己的计时器

示例定时器类:

public class Timer    {
        public Timer(int interval)
        {
            _interval = TimeSpan.FromMilliseconds(interval);
        }
        private bool _isRunning;
        private readonly TimeSpan _interval;
        private Action Tick;
        public void Start(Action tick)
        {
            _isRunning = true;
            Tick = tick;
            Xamarin.Forms.Device.StartTimer(_interval,() =>
            {
                Tick?.Invoke();
                return _isRunning;
            });
        }
        public void Stop()
        {
            _isRunning = false;
            Tick = null;
        }
    }

创建服务类。调用OnStartCommand方法中的DoWork方法。检查日志是否每隔5秒打印一次。

 public void DoWork()
            {
                var t = new Thread(() =>
                {
                    while (true)  
                    {
                       Log.Debug("Service", "Service running");    
                        Thread.Sleep(5000);
                    }
                });
                t.Start();
            }