我正在开展一个项目,我需要在不同的时间设置警报,例如在用户离开应用程序后的1天,3天,7天,28天之后。 我可以使用
轻松设置日常闹钟 Calendar calendar2 = Calendar.getInstance();
calendar2.set(Calendar.HOUR_OF_DAY, 16);
calendar2.set(Calendar.MINUTE, 40);
calendar2.set(Calendar.SECOND, 0);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar2.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
答案 0 :(得分:0)
我终于成功实现了这一目标。以下是解决方案
AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent();
if (screenPreferences.getInt("summary_page", 0) == 0 ) {
if(screenPreferences.getInt("alarm_set", 0) == 0){
screenPreferences.edit().putInt("alarm_set",1).commit();
startNotifications(alarmManager, intentArray, 1); // 1 is to start notifications
}
}else {
screenPreferences.edit().putInt("alarm_set",0).commit();
startNotifications(alarmManager, intentArray, 0); // 0 is to stop notifications
}
/************************************************************/
private void startNotifications(AlarmManager alarmManager, ArrayList<PendingIntent> intentArray, int onOrOff) {
for (int i = 0; i < 5; ++i) {
Intent intent = new Intent(MainActivity.this, StartReceiver.class);
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(MainActivity.this, i, intent, 0);
// Single alarms set for 1 day, 3 days, 7 days, 14 days, 28 days
if(onOrOff == 1){
long daySet = 60 * 60 * 24 * 1000;
switch (i){
case 0: daySet = 60 * 60 * 24 * 1000; // 1 day
break;
case 1: daySet = 60 * 60 * 72 * 1000; // 3 days
break;
case 2: daySet = 60 * 60 * 168 * 1000; // 7 days
break;
case 3: daySet = 60 * 60 * 336 * 1000; // 14 days
break;
case 4: daySet = 60 * 60 * 672 * 1000; // 28 days
break;
default:
daySet = 60 * 60 * 24 * 1000; // default 1 day
break;
}
alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + daySet, pendingIntent1);
intentArray.add(pendingIntent1);
}
else {
alarmManager.cancel(pendingIntent1);
}
}
}