问题
I set an alarm when the user lands on a certain activity, which is triggered after a certain time. How can I check if this alarm has already been triggered or not, so that it doesn't get set again if the user goes back to this activity ? I can only prevent the alarm getting set again if it's already scheduled but not triggered with this :
alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_NO_CREATE);
if (alarmIntent != null) {
// Alarm is already set
return;
}
alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
But this does not work if it's already triggered, as the alarm will be deleted afterwards so alarmIntent
will be null
回答1:
You can make use of shared preferences to check whether it is set or not.
if(!setFlag)
{
Intent myIntent = new Intent(FirstActivity.this, LogoutService.class);
pendingIntent = PendingIntent.getService(FirstActivity.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, 10); //Minutes
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
回答2:
Change PendingIntent PendingIntent.FLAG_CANCEL_CURRENT
alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT);
回答3:
You can just create a file the first time the alarm is run, and on next alarm runs you can check that the file already exists and you don't have to run the alarm again.
来源:https://stackoverflow.com/questions/46347911/how-to-trigger-an-alarm-only-once-in-android