Reputation: 2631
I have an e commerce app in which I have a list of elements which comes from backend, each item has its expiration duration like (5 minutes) for showing discount.
Each time I call api, it sends me remaining duration in millis (for example at the start it sends me 5 * 60 * 1000 = 300 000 milliseconds)
Now what I do is, I keep them in my presenter and start countdown by interval of 1000ms. On each tick, I subtract 1000ms from the time and update the remaining value for that item.
Problem is when I switch app to background, timer can be cancelled after some time (depending on the phone model), which causes the remaining duration to not be calculated
What would be the best way to update even when app is in background?
Upvotes: -1
Views: 36
Reputation: 1
To maintain the countdown timer while your app is in the background, you should consider using the WorkManager or Foreground Service approach instead of a simple CountDownTimer or Handler. The Android system may kill your app's background services, especially on certain manufacturers' devices that aggressively manage memory.
Here's a quick outline using WorkManager:
Create a Worker Class:
public class CountdownWorker extends Worker {
public CountdownWorker(@NonNull Context context, @NonNull WorkerParameters params) {
super(context, params);
}
@NonNull
@Override
public Result doWork() {
long remainingTime = getInputData().getLong("remaining_time", 0);
// Your logic to handle countdown and update database/SharedPreferences
return Result.success();}
}
2.Enqueue Work:
Data data = new Data.Builder()
.putLong("remaining_time", remainingMillis)
.build();
OneTimeWorkRequest countdownWork = new OneTimeWorkRequest.Builder(CountdownWorker.class)
.setInputData(data)
.build();
WorkManager.getInstance(context).enqueue(countdownWork);
User’s should check out the Android WorkManager documentation for more intricate control over timing and constraints.
Optionally, if you want immediate actions and you are dealing with a very short countdown, then using a Foreground Service can also be beneficial. But remember, this keeps the notification visible to the user while maintaining the process awake.
Note: Always remember to handle users with Android 8.0 (API level 26) and above, as the system imposes limitations on background tasks.
Upvotes: 0