I want to set repeating alarm that triggers every

2019-02-25 19:51发布

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.

2条回答
倾城 Initia
2楼-- · 2019-02-25 20:24

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.

查看更多
在下西门庆
3楼-- · 2019-02-25 20:36

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.

查看更多
登录 后发表回答