【问题标题】:Alarm app prevent Change of system time警报应用程序防止更改系统时间
【发布时间】:2018-04-27 12:26:29
【问题描述】:

我的应用程序是这样工作的,用户以分钟为单位记下时间,例如 40。然后应用程序将在 40 分钟后发出警报。无论应用是处于活动状态还是在后台运行,它仍然可以工作。

我的问题是,因为我使用 System.currentTimeMillis();然后它使我的应用程序依赖于系统时间。因此,如果我在设置中更改我的系统时间,那么我的闹钟应用程序将不会在设定的时间被调用,它会改变。

例如:如果时间是上午 10:00,我将闹钟设置为从现在起 20 分钟后响起,那么它将被称为上午 10:20。但是,如果我在设置闹钟后进入设置并将系统时间更改为上午 9:00,那么我的应用程序将从现在开始 100 分钟被调用。我该如何防止这种情况发生,以便在设置闹钟时间时,无论系统时间是什么,都会在这些分钟后调用闹钟。

这是我的代码:

public void newSetAlarm(View view) {


        timeEntered = Integer.parseInt(editTextForTime.getText().toString());
        Intent AlarmIntent = new Intent(this, Alarm.class);
        AlarmIntent.putExtra(TIME_LEFT, timeEntered);
        pendingIntentForAlarm = PendingIntent.getBroadcast(getApplicationContext(), 0, AlarmIntent, 0);
        amAlarm = (AlarmManager) getSystemService(ALARM_SERVICE);
        amAlarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeEntered * 60000, pendingIntentForAlarm);}

设法解决了这个问题

<receiver android:name=".TimeChangeBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.TIME_SET"/>
<action android:name="android.intent.action.TIMEZONE_CHANGED"/>
</intent-filter>

在清单文件中,然后创建该类

 public class TimeChangeBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
DoWhatEverYouWantHere();

}}

现在的问题是,每当我更改设置中的时间时,都会调用此广播接收器。但我只希望在我的闹钟运行时调用它,并且用户可以进行设置以更改时间。当没有警报,并且用户在设置中更改时间时,我不希望广播接收器在后台运行。

我该如何解决

【问题讨论】:

标签: java android time broadcastreceiver


【解决方案1】:

设置闹钟时不要使用RTC_WAKEUP,而是使用ELAPSED_REALTIME_WAKEUP。确保您提供 NOW 与您希望警报触发的时间之间的增量作为“触发”时间而不是时钟时间。

经过的实时测量设备启动后的时间。当设备的时钟改变时它不会改变。如果您这样做,则无需处理时钟或时区更改。

阅读https://developer.android.com/reference/android/os/SystemClock,了解有关您可以使用的不同时钟以及您应该在哪种情况下使用哪个时钟的详细信息。

【讨论】:

  • 所以我应该将 `amAlarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeEntered * 60000, pendingIntentForAlarm);` 更改为:` amAlarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis( ) + timeEntered * 60000, pendingIntentForAlarm);`。它会这样做吗?
  • 没有。使用amAlarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + timeEntered * 60000, pendingIntentForAlarm);。您调用elapsedRealtime() 以获取自上次启动设备以来的毫秒数。这对应于ELAPSED_REALTIME_WAKEUP 的“现在时间”。
  • 谢谢!我现在知道了。我会尝试看看它是否有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 2023-03-25
  • 1970-01-01
  • 2012-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多