首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Android中的日期和时间更改侦听器?

Android中的日期和时间更改侦听器?
EN

Stack Overflow用户
提问于 2011-03-30 10:59:29
回答 3查看 59K关注 0票数 68

在我的应用程序中,有一个警报服务,我发现如果用户将它的日期或时间更改为过去的时间。我的警报不会在我预期的时间触发。

所以,我可能要重新设置所有的警报。android中有日期和时间更改监听器吗?

EN

回答 3

Stack Overflow用户

发布于 2017-06-08 08:02:33

除了被接受的答案之外

如果你想在你的应用程序不运行时监听时间变化,我会在清单中注册:

代码语言:javascript
复制
<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>

如果这样做,请不要在代码中使用registerReceiverunregisterReceiver显式注册接收器。

再说一次,这只是对公认答案的补充。

票数 30
EN

Stack Overflow用户

发布于 2019-11-09 15:33:20

Ben的答案的Java版本,只做了一个小的修正。修复方法是将ACTION_TIME_TICK添加为我们应该关注的广播接收器操作之一。

代码语言:javascript
复制
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;
}

}

票数 0
EN

Stack Overflow用户

发布于 2020-03-16 10:55:31

在清单中注册BroadcastReceiver时的另一个补充

当您当前没有活动告警时,您可能希望停止收听广播,并在稍后有活动告警时重新启用。

代码语言:javascript
复制
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
)

Sauce

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5481386

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档