0

I have a simple app that counts steps using Sensor.TYPE_STEP_DETECTOR. This sensor is NOT unregistered after the app is set into the background, meaning it continues to track steps even when it's not in focus. Once the app resumes, the step counter UI gets updated with whatever steps were counted since it was last in focus.

My goal is to have the app save the data after it's been closed in the background. It already saves it onPause() but I haven't found any method related to when the app is closed.

At first, onDestroy() seemed like the obvious place, but it's not guaranteed to be called since it only seems to be called when something calls finish() or if the system wants to clear up space.

I've also seen solutions involving using a background service or Job Scheduler. A background service wouldn't work since as of API >= 26 the background services stop after several minutes. I think Job Scheduler wouldn't work since I won't know when the user might close the app and I want the steps to be as accurate as possible, so finding an interval for when to schedule the jobs would be difficult.

I'm looking for a simple spot to basically do what my onPause() method already does.

@Override
protected void onPause() {
    super.onPause();

    saveSteps(currentSteps);
    running = false;
}
Jefumaru
  • 1
  • 2

1 Answers1

0

What is exactly the problem? Do you just want to replicate the onResume somewhere else? If so you could do that at the onRestart/onResume function since the sensor isn't unregistered you could get the same results , but I don't see how that would change things for you.

  • The problem is that once the app is closed by the user, the steps that have been counting in the step sensor aren't saved, since there are no methods as far as I know that are called when the app is closed. Ex: 100 steps are saved in onPause(), when the app is set to the background. The sensor continues counting steps, so now there are 105 steps. When the app is closed though, there is nothing saving it. So when I start the app again, it shows 100 steps since that was the last amount saved. – Jefumaru Sep 28 '19 at 15:58
  • I should clarify that when I say "closed" I mean clicking the X in the corner or swiping it away when bringing up the list of open applications. – Jefumaru Sep 28 '19 at 16:10
  • Assuming you have tried onPause as you said onDestroy and lastly onStopped , I guess it would be good if you tried to use a service for counting on the background and then adding it to the last saved instance ( while the app was running essentially) https://stackoverflow.com/questions/30525784/android-keep-service-running-when-app-is-killed check this out I think that should help you – Michael Mouzakitis Sep 29 '19 at 20:36
  • According to this, background services go idle after several minutes. This app could potentially be going for as long as the phone is on: https://developer.android.com/about/versions/oreo/background – Jefumaru Oct 02 '19 at 15:50