我在我的Xamarin Android应用程序中使用了一个AlarmManager。我使用SetExact()配置它,时间为5分钟。但它只在5秒后启动。无论我用什么时间配置它,它总是在5秒后触发。我在Java中使用了完全相同的代码,它完美地工作了。
代码:
我如何使用
代码:
[BroadcastReceiver]
public class AlarmReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Log.Info("AlarmReceiver", "Triggered");
}
public static void Start(Context context, long triggerAfterMilis)
{
var type = AlarmType.RtcWakeup;
var alarmManager = (AlarmManager) context.GetSystemService(Context.AlarmService);
var timerIntent = PendingIntent.GetBroadcast(context, 0, new Intent(context, typeof(AlarmReceiver)), PendingIntentFlags.CancelCurrent);
alarmManager.Cancel(timerIntent);
if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
alarmManager.SetAndAllowWhileIdle(type, triggerAfterMilis, timerIntent);
else if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
alarmManager.SetExact(type, triggerAfterMilis, timerIntent);
else
alarmManager.Set(type, triggerAfterMilis, timerIntent);
Log.Info("AlarmReceiver", $"Started, tigger after {triggerAfterMilis} miliseconds.");
}
}
我如何使用
AlarmReceiver
:AlarmReceiver.Start(Activity,(long)TimeSpan.FromMinutes(10).TotalMilliseconds)
输出窗口:
14:14:20.217 5393-5393/AlarmReceiver:已启动,触发时间为600000毫秒。14:14:25.218 5393-5393/AlarmReceiver:已触发