如何在指定时间发送PendingIntent

时间:2018-03-13 09:28:23

标签: java android

我有两个alarmManager类的实例。并设置一个:

        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.HOUR_OF_DAY, hour);
        calendar.set(calendar.MINUTE, min);
        long sdl = calendar.getTimeInMillis();
        Intent intent123 = new Intent(this,AlarmReceiver.class);
        int _id = (int) System.currentTimeMillis();
        PendingIntent appIntent = PendingIntent.getBroadcast(MainActivity.this, _id, intent123,PendingIntent.FLAG_IMMUTABLE);
        alarmManager = (AlarmManager) MainActivity.this.getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, sdl, appIntent);

hourmin来自用户。

并设置第二名:

   AlarmManager alarmManager = (AlarmManager) ActivityTimePicker.this.getSystemService(Context.ALARM_SERVICE);
   Calendar calendar = Calendar.getInstance();
   calendar.set(calendar.HOUR_OF_DAY, 24);
   calendar.set(calendar.MINUTE, 00);


   long sdl = calendar.getTimeInMillis();
   Intent intent = new Intent(this,Main2Activity.class);
   PendingIntent appIntent = PendingIntent.getActivity(this.getBaseContext(), 4534534, intent,PendingIntent.FLAG_CANCEL_CURRENT);
    alarmManager.set(AlarmManager.RTC_WAKEUP, sdl, appIntent);

这将每24小时发送一次。 但问题是两者都被发送了。但我想在自己的时间发送每一个。 解决方案是什么? 谢谢!

1 个答案:

答案 0 :(得分:0)

public static void setReminder(Context context,Class<?> cls,int hour, int min)
    {
        Calendar calendar = Calendar.getInstance();

        Calendar setcalendar = Calendar.getInstance();
        setcalendar.set(Calendar.HOUR_OF_DAY, hour);
        setcalendar.set(Calendar.MINUTE, min);
        setcalendar.set(Calendar.SECOND, 0);

        // cancel already scheduled reminders
        cancelReminder(context,cls);

        if(setcalendar.before(calendar))
            setcalendar.add(Calendar.DATE,1);

        // Enable a receiver

        ComponentName receiver = new ComponentName(context, cls);
        PackageManager pm = context.getPackageManager();

        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);


        Intent intent1 = new Intent(context, cls);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP, setcalendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

    }

更多信息请参阅此链接:https://github.com/jaisonfdo/RemindMe/blob/master/app/src/main/java/com/droidmentor/remindme/NotificationScheduler.java