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

时间:2016-09-02 07:10:06

标签: c# android xamarin xamarin.android alarmmanager

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

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

4 个答案:

答案 0 :(得分:1)

在“活动”中的IntentService(如果我们可以调用它)在应用程序的后台运行,所以最终会调用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/

答案 1 :(得分:0)

希望此代码可以帮助您:-

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

在需要的地方调用“ StartTimer()”方法。仅呼叫一次,然后在60秒后自动呼叫。

谢谢!!!

答案 2 :(得分:0)

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

示例计时器类:

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

答案 3 :(得分:-1)

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

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