如何在Android中仅触发一次警报?

问题描述:

我设置了一个警报,当用户登陆某个特定活动时,该警报会在特定时间后触发。
如何检查此警报是否已触发,以便用户返回到该活动时不会再次设置该警报?
我只能阻止已设置但未通过此方式触发的警报再次设置:

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);

但是如果已经触发,则此方法不起作用,因为警报将在以后删除,因此 alarmIntent 将为 null

But this does not work if it's already triggered, as the alarm will be deleted afterwards so alarmIntent will be null

您可以使用共享的首选项来检查是否已设置。

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);
}