如何在Android中仅触发一次警报? [英] How to trigger an alarm only once in Android?

查看:124
本文介绍了如何在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);
}

这篇关于如何在Android中仅触发一次警报?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆