Android:即使尚未达到触发时间,AlarmManager也会调用我的广播接收器

时间:2016-04-25 06:26:31

标签: android broadcastreceiver alarmmanager

我遇到了报警管理器和广播的麻烦。这是我的代码,它在一小时内安排任务。

var preference = PreferenceManager.GetDefaultSharedPreferences (Application.Context);
        var alarmManager = (AlarmManager)Application.Context.GetSystemService (Application.AlarmService);  
        var intent = new Intent (Application.Context, typeof(ScheduleUsageLogReceiver));
        var schedule = new LogSchedule (1);
        var serializer = new DataContractJsonSerializer (typeof(LogSchedule));

        if (preference.Contains (ScheduleUsageLogReceiver.SHARE_PREFERENCE_USAGE_NAME))
            return; 

        using (MemoryStream ms = new MemoryStream())
        {
            serializer.WriteObject(ms, schedule);
            var json = Encoding.Default.GetString(ms.ToArray());
            var editor = preference.Edit ();
            editor.PutString (ScheduleUsageLogReceiver.SHARE_PREFERENCE_USAGE_NAME, json);
            editor.Commit ();
        }

        var pendingIntent = PendingIntent.GetBroadcast (Application.Context, 0, intent, 0);
        alarmManager.Set (AlarmType.Rtc, schedule.NumberMillisecondToLog, pendingIntent);

接收时间表的广播接收器是

[BroadcastReceiver]
[IntentFilter (new string[] { Android.Content.Intent.ActionShutdown, "com.htc.intent.action.QUICKBOOT_POWEROFF", Android.Content.Intent.ActionBootCompleted } )]
public class ScheduleUsageLogReceiver : BroadcastReceiver
{
    public const string SHARE_PREFERENCE_USAGE_NAME = "ScheduleUsageLogReceiver"; 

    public override void OnReceive (Context context, Intent intent)
    {
        Toast.MakeText (context, "Received intent!", ToastLength.Short).Show ();}}

我有一个bootComplete动作和关机动作,但我做了一个断点,但意图并没有包含这些动作,所以我不认为这是问题所在。

我已经检查过触发时间是3600000但是我不知道为什么在编译和运行应用程序时它会立即触发。

1 个答案:

答案 0 :(得分:0)

如果您要在过去一段时间内创建警报的PendingIntent,则会立即触发。检查并确认您提供的时间不是通过/当前时间。