使用AlarmManager将多个pendingIntent调度到同一个活动

时间:2012-05-12 05:51:03

标签: android android-intent alarmmanager android-calendar android-pendingintent

最近,当我尝试使用AlarmManager计划将来运行活动时,我注意到了一些奇怪的行为。查看下面的代码,第一个活动在20秒内启动,而第二个活动不是在40秒内启动,而是在60秒后启动。任何人都可以解释为什么第二个意图没有安排调用第二个活动而不是第三个意图。这是否意味着我只能对AlarmManager中的活动有一个意图。

//pending intent for morning
    Intent myIntent1 = new Intent(this, Activity1.class);
    pendingIntent1 = PendingIntent.getActivity(this, 0, myIntent1, 0);
    AlarmManager alarmManager1 = (AlarmManager)getSystemService(ALARM_SERVICE);
    Calendar calendar1 = Calendar.getInstance();
    //calendar1.set(Calendar.YEAR, Calendar.MONTH + 1, Calendar.DAY_OF_MONTH, morningTime, 0, 0);
    calendar1.setTimeInMillis(System.currentTimeMillis());
    calendar1.add(Calendar.SECOND, 20);
    alarmManager1.set(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), pendingIntent1);

    //pending intent for noon
    Intent myIntent2 = new Intent(this, Activity2.class);
    pendingIntent2 = PendingIntent.getActivity(this, 0, myIntent2, 0);
    AlarmManager alarmManager2 = (AlarmManager)getSystemService(ALARM_SERVICE);
    Calendar calendar2 = Calendar.getInstance();
    //calendar2.set(Calendar.YEAR, Calendar.MONTH + 1, Calendar.DAY_OF_MONTH, noonTime, 0, 0);
    calendar2.setTimeInMillis(System.currentTimeMillis());
    calendar2.add(Calendar.SECOND, 40);
    alarmManager2.set(AlarmManager.RTC_WAKEUP, calendar2.getTimeInMillis(), pendingIntent2);

    //pending intent for night
    Intent myIntent = new Intent(this, Activity2.class);
    pendingIntent = PendingIntent.getActivity(this, 0, myIntent, 0);
    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance();
    //calendar.set(Calendar.YEAR, Calendar.MONTH + 1, Calendar.DAY_OF_MONTH, nightTime, 0, 0);
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add(Calendar.SECOND, 60);
    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);'

1 个答案:

答案 0 :(得分:15)

  

这是否意味着我只能对AlarmManager中的活动有一个意图。

不,但这意味着您需要不同的PendingIntents。你在打电话:

Intent myIntent = new Intent(this, Activity2.class);
pendingIntent = PendingIntent.getActivity(this, 0, myIntent, 0);

两次,因此两个getActivity()调用返回相同的PendingIntent

或者:

  • getActivity()的第二个参数使用不同的值,或

  • Intent个对象执行某些操作以使它们充分不同,例如使用不同的操作字符串(注意:额外内容不足)