【问题标题】:Android AlarmManager: how to find out the time remaining to trigger the PendingIntentAndroid AlarmManager:如何找出触发 PendingIntent 的剩余时间
【发布时间】:2014-06-24 13:23:33
【问题描述】:

我正在开发一个闹钟应用程序。下面我有一个设置闹钟的功能。但是我想知道如何找到AlarmManager触发PendingIntent的剩余时间。

比如现在是上午10:00,设置AlarmManager在23:00触发PendingIntent,计算我们知道PendingIntent会在这里13小时被调用。但是如何找出剩余的时间呢?

对不起,我的英语很差。感谢您的关注

String schedule = "23:00"; //example

Calendar cal = Calendar.getInstance();
cal.set(cal.HOUR_OF_DAY, getTime(schedule));
cal.set(cal.MINUTE, getMinute(schedule));
cal.set(cal.SECOND, 0);
cal.set(cal.MILLISECOND, 0);

DateFormat dfH = new SimpleDateFormat("HH");
DateFormat dfM = new SimpleDateFormat("mm");
int currentTime = Integer.parseInt(dfH.format(new Date()));
int currentMinute = Integer.parseInt(dfM.format(new Date()));


Intent i = new Intent(context, RecebAlarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context.getApplicationContext(), id, i, 0);
AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
long totalTime = cal.getTimeInMillis();

if (currentTime > getTime(schedule) || (currentTime == getTime(schedule) && currentMinute >= getMinute(schedule))) {
    alarms.set(AlarmManager.RTC_WAKEUP, totalTime + AlarmManager.INTERVAL_DAY, pi);
} else {
    alarms.set(AlarmManager.RTC_WAKEUP, totalTime, pi); 
}

【问题讨论】:

    标签: java android alarmmanager android-pendingintent


    【解决方案1】:

    您可以像这样计算您的闹钟时间 (totalTime) 和当前时间之间的差异:

    long timeDiffInMillis = totalTime - System.currentTimeMillis();
    

    这将为您提供警报触发前的剩余时间(以毫秒为单位)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 2021-10-26
      • 1970-01-01
      相关资源
      最近更新 更多