警报应用程序防止更改系统时间

Alarm app prevent Change of system time

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

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

例如:如果时间是10:00am,我设置了从现在起20分钟后叫闹钟,那么它就会叫10:20am。但是,如果我在设置闹钟后进入设置并将系统时间更改为 9:00am,那么我的应用程序将从现在起 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>

在清单文件中,然后创建 class

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

}}

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

我该如何解决

设置闹钟时不要使用RTC_WAKEUP,而是使用ELAPSED_REALTIME_WAKEUP。确保您提供现在和您希望警报触发的时间之间的差值作为 "trigger" 时间而不是时钟时间。

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

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