Я хочу выполнять какие-то действия каждый день в 12:00. Действие выполняется только один раз в тот день, когда приложение устанавливается, но, к сожалению, это не работает на следующий день (12:00)
Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
if(alarmManager!=null) {
alarmManager.cancel(pendingIntent);
}
Calendar firingCal = Calendar.getInstance();
Calendar currentCal = Calendar.getInstance();
firingCal.set(Calendar.HOUR_OF_DAY, 0); // At the hour you wanna fire
firingCal.set(Calendar.MINUTE, 0); // Particular minute
firingCal.set(Calendar.SECOND, 0); // particular second
long intendedTime = firingCal.getTimeInMillis();
long currentTime = currentCal.getTimeInMillis();
if (intendedTime >= currentTime) {
// you can add buffer time too here to ignore some small differences in milliseconds
// set from today
Log.d("MainActivity", "startAt12: set from today "+currentCal.getTime());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
} else {
// set from next day
// you might consider using calendar.add() for adding one day to the current day
firingCal.add(Calendar.DAY_OF_MONTH, 1);
intendedTime = firingCal.getTimeInMillis();
Log.d("MainActivity", "startAt12: set from next day "+firingCal.getTime());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
}
И это мой приемник Broadcast
public class AlarmReceiver extends BroadcastReceiver {
Intent intentService;
@Override
public void onReceive(Context context, Intent intent) {
Log.d("onReceive", " AlarmReceiver onReceive: ");
intentService = new Intent(context, MyService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intentService);
} else {
context.startService(new Intent(intentService));
}
Toast.makeText(context, "Call activity fired after 24 hour", Toast.LENGTH_SHORT).show();
}
}