首页 文章

每隔几秒就收到一次TIMEZONE_CHANGED意图

提问于
浏览
10

我使用带有TIMEZONE_CHANGED操作的BroadcastReceiver来使用AlarmManager重置警报,以确保警报在设定的时间运行,而不是提前几小时或更晚,具体取决于时区的变化 .

然而,在用户发送的最新日志中,我看到有关每隔几秒钟收到TIMEZONE_CHANGED操作的意图的信息,用户抱怨应用程序出现故障 .

这是我的BroadcastReceiver的onReceive代码

@Override
public void onReceive(Context context, Intent intent) {
    Utils.log("OnTimeChange");
    String action = intent.getAction();

    if (action.equals(Intent.ACTION_TIME_CHANGED)) {
        Utils.log("TimeChange");
    } else if (action.equals(Intent.ACTION_TIMEZONE_CHANGED)) {
        Utils.log("TimeZoneChanged");
    }
    BroadcastsManager.updateBroadcastsFromAlarms(context,
            AlarmsDbAdapter.getInstance(context));
}

清单的意图过滤器:

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

和日志的一部分(它超过一个小时 - 完整的日志长度)

1. 19/4 7:41:54 - posting alarm 3 for 8:15 (in 0h)
2. 19/4 7:44:29 - OnTimeChange
3. 19/4 7:44:29 - TimeZoneChanged
4. 19/4 7:44:29 - posting alarm 3 for 8:15 (in 0h)
5. 19/4 7:44:54 - OnTimeChange
6. 19/4 7:44:54 - TimeChange
7. 19/4 7:44:54 - posting alarm 3 for 8:15 (in 0h)

这是三星Galaxy S III(Android v 4.1.2) . 奇怪的是,这不会发生在我的S III上 . 可能是用户在他/她的设备上设置了“按提供商自动更改时区”选项,并且每隔几秒发送一次这样的信息?

有人有过期吗?我想我会在更新广播之前添加一个选项来检查时区是否实际发生了变化,但它仍然每隔几秒就会调用一次接收器......

2 回答

  • 9

    我仍然不知道为什么经常调用时区更改和时间设置,但我能够找到一个解决方案,让我找出实际需要反应的时间 .

    此外,我现在只收听时区变化 .

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    
    String oldTimezone = prefs.getString(PREF_TIMEZONE, null);
    String newTimezone = TimeZone.getDefault().getID();
    
    long now = System.currentTimeMillis();
    
    if (oldTimezone == null || TimeZone.getTimeZone(oldTimezone).getOffset(now) != TimeZone.getTimeZone(newTimezone).getOffset(now)) {
         prefs.edit().putString(PREF_TIMEZONE, newTimezone).commit();
         Logger.log("TimeZone time change");
        //update alarms
    }
    

    我添加了区域的时间检查,因为我经常发现,虽然区域改变了,但它们在时间上没有任何不同 . 还有一些用户声称,当检测到区域发生多次变化时,他们甚至都没有去过任何地方 - 只是定期上班和返回 .

    检查有限数量的不需要的操作 .

  • 0

    避免倾听:

    <action android:name="android.intent.action.TIME_SET" />
    <action android:name="android.intent.action.TIMEZONE_CHANGED" />
    

    似乎在没有设定时间和时区改变的情况下也会定期调用它们 . 我怀疑它与用户在手机设置中使用“使用网络提供的时区和时间”链接 .

    如果你真的需要监听这些广播,你应该检查时间是否确实发生了显着变化,或者它是否只是从网络提供的毫秒修正时间

相关问题