The Android Awareness API has recently announced new features that provide a simple solution for your use case (this avoids explicitly managing a location request or calculating sunrise times). The way to achieve what you are trying to do is to create and register a TimeFence specified regarding sunrise / sunset.
For instance:
// 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 receive callbacks when the fence evaluates to TRUE at sunrise, and when it returns to FALSE 5 minutes after sunrise.
Please check the Fence API code snippets to add custom application logic.
source share