安排一个以上的PendingIntent使用AlarmManager同一活动(Scheduling

2019-09-17 04:57发布

最近我注意到奇怪的现象,当我试图计划使用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);'

Answer 1:

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

没有,但它意味着你需要不同的PendingIntents 。 您在呼唤:

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

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

或者:

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

  • 做一些事情来的Intent对象,使他们充分不同,如使用不同的操作字符串(注:演员是不够的)



文章来源: Scheduling more than one pendingIntent to same activity using AlarmManager