I want to set repeating alarm that triggers every day at different time

会有一股神秘感。 提交于 2019-12-02 03:46:28

问题


I need the alarm to be triggered every day at sunrise. I get the sunrise time like this:"06:55"

Location location = new Location(latitude, longitude);
SunriseSunsetCalculator calculator = new SunriseSunsetCalculator(location, "GMT"+localTime);
String officialSunrise = calculator.getOfficialSunriseForDate(Calendar.getInstance());

That means every day the time to trigger will be different.

alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, startmillis,intervalmillis, wakeUp); 

I would appreciate general guidance on what direction to go.


回答1:


Instead of setting an alarm that will go off at a different time each day. You should set separate alarms each day. I recommend you do this by setting the next days alarm after an alarm goes off.




回答2:


Android Awareness API has recently announced new features that provide a simple solution for your use-case (that avoids you having to explicitly manage location request and computing sunrise times). The way to achieve what you're trying to do is to create and register a TimeFence specified relative to sunrise/sunset.

For example:

// Create TimeFence
AwarenessFence sunriseFence =
    TimeFence.aroundTimeInstant(TimeFence.TIME_INSTANT_SUNRISE,
        0, 5 * ONE_MINUTE_MILLIS);

// Register fence with Awareness.
Awareness.FenceApi.updateFences(
    mGoogleApiClient,
    new FenceUpdateRequest.Builder()
        .addFence("fenceKey", sunriseFence, myPendingIntent)
        .build())
    .setResultCallback(new ResultCallback<Status>() {
        @Override
        public void onResult(@NonNull Status status) {
            if (status.isSuccess()) {
                Log.i(TAG, "Fence was successfully registered.");
            } else {
                Log.e(TAG, "Fence could not be registered: " + status);
            }
        }
    });

You will get callbacks when the fence evaluates to TRUE at sunrise, and when it evaluates back to FALSE at 5-min after sunrise based on the settings above.

Please check Fence API code snippets docs for how to add your custom app logic.



来源:https://stackoverflow.com/questions/18950630/i-want-to-set-repeating-alarm-that-triggers-every-day-at-different-time

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