Timertask 运行() 方法在 2 小时之类的较长时间内无法正常工作

Timertask Run() method is not working for longer period like 2 hours

创建了一个自己的应用程序,尽管它被用户使用 Timertask class 运行 方法删除或关闭,但它会自动启动,但它可以正常延迟长达 15 分钟和 20 分钟,但运行 延迟 2 小时后操作无效。这是我的代码

timerTask = new LoginTimerTask(this);
timer.Schedule(timerTask,(long) TimeSpan.FromHours(2).TotalMilliseconds , (long)TimeSpan.FromHours(2).TotalMilliseconds);

 public class LoginTimerTask : TimerTask
    {
        MainActivity mainActivity;

        public LoginTimerTask(MainActivity activity)
        {
            mainActivity = activity;
        }

        public override void Run()
        {
            var intent = new Intent(mainActivity, typeof(MainActivity));
            mainActivity.StartActivity(intent);
        }
    } 

首先添加这个权限

<uses-permission android:name="android.permission.WAKE_LOCK" />

更新:你还必须在后台使用 运行 的服务,使用下面的代码

using System;
using System;
using System.Threading;
using Android.App;
using Android.Content;
using Android.OS;
using OomaAndroid.Models;
using SQLite;

namespace OomaAndroid
{
    [Service]
    public class ServiceTest : Service
    {
        Timer timer;        
        public override void OnCreate()
        {
            base.OnCreate();
        }
        public override IBinder OnBind(Intent intent)
        {            
            return null;
        }


        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {            
            timer = new Timer(HandleTimerCallback, 0, 0, 43200000);
            return base.OnStartCommand(intent, flags, startId);
        }

        private void HandleTimerCallback(object state)
        {
            //Start your Activity Here, it runs every 2 hours
            var intent = new Intent(mainActivity, typeof(MainActivity));
            mainActivity.StartActivity(intent);
        }
    }    
}

还有你运行你的服务曾经在主要activity

  Intent intSer = new Intent(base.ApplicationContext, typeof(ServiceTest));
  StartService(intSer);

使用警报管理器解决了这个问题。

 public void startAlert()
        {
            var alarmIntent = new Intent(this, typeof(AlarmReceiver));
            var pending = PendingIntent.GetBroadcast(this, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
            var alarmManager = GetSystemService(AlarmService).JavaCast<AlarmManager>();
            alarmManager.Set(AlarmType.ElapsedRealtime,(long)(SystemClock.ElapsedRealtime() + TimeSpan.FromHours(2).TotalMilliseconds), pending);
        }

    [BroadcastReceiver]
    public class AlarmReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            intent = new Intent(context, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.NewTask);
            context.StartActivity(intent);
        }
    }