【发布时间】: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();
}}
现在的问题是,每当我更改设置中的时间时,都会调用此广播接收器。但我只希望在我的闹钟运行时调用它,并且用户可以进行设置以更改时间。当没有警报,并且用户在设置中更改时间时,我不希望广播接收器在后台运行。
我该如何解决
【问题讨论】:
-
我已尝试关注此链接stackoverflow.com/questions/5481386/…,但效果不佳。
标签: java android time broadcastreceiver