如何在Android AlarmManager中安排未来的重复闹钟?

时间:2017-01-23 17:32:47

标签: android notifications alarmmanager

我可以使用以下代码在Android中设置重复闹钟。但问题是,它也会立即发出通知,我不希望这样。我只是希望用户输入他们希望闹钟响起的时间,并在此时关闭闹钟并以选定的给定间隔重复。我尝试切换ELAPSED_REALTIME_WAKEUP而不是RTC_WAKEUP但是该代码对我不起作用。

ax

提前致谢!!!

1 个答案:

答案 0 :(得分:0)

这就是我使用的。

public class AlarmHelper {
    private static final String TAG = "AlarmHelper";
    private static final int REQUEST_CODE = 12377;
    private static final int REQUEST_CODE_OVERTIME = 12376;

    private AlarmHelper() {
    }

    public static void scheduleAlarm(Context c) {
        AlarmManager manager = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(c, REQUEST_CODE, new Intent(c, ClockInBroadcastReceiver.class), PendingIntent.FLAG_CANCEL_CURRENT);


        //Set next clock-in time
        GregorianCalendar time = new GregorianCalendar();
        time.add(...,...); //Whatever you want to add.


        if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            manager.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis() + 1000, pendingIntent);
        } else if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            manager.setExact(AlarmManager.RTC_WAKEUP, time.getTimeInMillis() + 1000, pendingIntent);
        } else {
            manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time.getTimeInMillis() + 1000, pendingIntent);
        }

    }

}