How to detect Daylight Saving Time transition in android

三世轮回 提交于 2019-12-05 12:14:35

Well, here is how I resolved this issue:

1- I kept the Android Manifest as it is (see the question)

2- Then i changed the receiver a bit:

public class NotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        WakeLock.acquire(context);
        // Timezone or time change
        if (intent.getAction() != null
            && (intent.getAction().equals(Intent.ACTION_TIME_CHANGED)
            || intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)))
        {
            calculateTimeZone(context);
        }
    }
}

3- Here is the method that calculates the new timezone and the use of DST:

public void calculateTimeZone(Context context) {
    float ONE_HOUR_MILLIS = 60 * 60 * 1000;

    // Current timezone and date
    TimeZone timeZone = TimeZone.getDefault();
    Date nowDate = new Date();
    float offsetFromUtc = timeZone.getOffset(nowDate.getTime()) / ONE_HOUR_MILLIS;

    // Daylight Saving time
    if (timeZone.useDaylightTime()) {
        // DST is used
        // I'm saving this is preferences for later use

        // save the offset value to use it later
        float dstOffset = timeZone.getDSTSavings() / ONE_HOUR_MILLIS;
        // DstOffsetValue = dstOffset
        // I'm saving this is preferences for later use

        // save that now we are in DST mode
        if (timeZone.inDaylightTime(nowDate)) {
            // Now you are in use of DST mode
            // I'm saving this is preferences for later use
        } else {
            // DST mode is not used for this timezone
            // I'm saving this is preferences for later use
        }
    }
}

That's it. So, the solution was to combine all the ApIs (listed in the question) together.

I hope that this solution will help other. If you have any question just post it in comment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!