在我的应用程序中,有一个警报服务,我发现如果用户将它的日期或时间更改为过去的时间。我的警报不会在我预期的时间触发。
所以,我可能要重新设置所有的警报。android中有日期和时间更改监听器吗?
发布于 2017-06-08 08:02:33
除了被接受的答案之外
如果你想在你的应用程序不运行时监听时间变化,我会在清单中注册:
<receiver android:name="com.your.pacakge.TimeChangeBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.TIME_SET"/>
<action android:name="android.intent.action.TIMEZONE_CHANGED"/>
</intent-filter>
</receiver>
如果这样做,请不要在代码中使用registerReceiver
和unregisterReceiver
显式注册接收器。
再说一次,这只是对公认答案的补充。
发布于 2019-11-09 15:33:20
Ben的答案的Java版本,只做了一个小的修正。修复方法是将ACTION_TIME_TICK添加为我们应该关注的广播接收器操作之一。
public abstract class DayChangedBroadcastReceiver extends BroadcastReceiver {
private Date date = new Date();
private DateFormat dateFormat = new SimpleDateFormat("yyMMdd", Locale.getDefault());
public abstract void onDayChanged();
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Date currentDate = new Date();
if (action != null && !isSameDay(currentDate) &&
(action.equals(Intent.ACTION_TIME_CHANGED)
|| action.equals(Intent.ACTION_TIMEZONE_CHANGED)
|| action.equals(Intent.ACTION_TIME_TICK))) {
date = currentDate;
onDayChanged();
}
}
private boolean isSameDay(Date currentDate) {
return dateFormat.format(currentDate).equals(dateFormat.format(date));
}
public static IntentFilter getIntentFilter() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_TIME_TICK);
intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
return intentFilter;
}
}
发布于 2020-03-16 10:55:31
在清单中注册BroadcastReceiver时的另一个补充
当您当前没有活动告警时,您可能希望停止收听广播,并在稍后有活动告警时重新启用。
val receiver = ComponentName(context, SampleBootReceiver::class.java)
context.packageManager.setComponentEnabledSetting(
receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
// or PackageManager.COMPONENT_ENABLED_STATE_DISABLED to disable it
PackageManager.DONT_KILL_APP
)
https://stackoverflow.com/questions/5481386
复制相似问题