There is an application that contains the activity MainActivity . The activity is collecting GPS coordinates (in the background) and sending them to the server.

If you start the application and "forget" about it, then it works for a while (maximum hour), i.e. collects coordinates, and timers running in onCreate() work. Then the application hangs in the open, but does nothing, the log does not write. If you activate it, then everything works fine again.

I wrote a task for him through AlarmManager , so that every minute just write to the log. Creating a class object in which alarm is registered occurs in the overloaded onCreate() . After that, the application stopped falling asleep. However, on some devices it may still fall asleep after a few hours. In this case, the Alarm log is stable.

I decided to track the life cycle of the application and saw that after the main form becomes inactive, OnStop() and OnDestroy() always executed immediately. Those. processes continue to work after OnDestroy() . But then they can be put to sleep.


Please advise me how to periodically activate the application (maybe you can somehow initiate the onCreate() call) so that the processes started by the timers are not put to sleep. Thank.

  • 2
    To work in the background there is a Service. Activation is not suitable for such tasks. - Nikotin N
  • And if I need an interface to display activity and various states, how? From the activation to start the service, and from the service to access the activation elements? - Eugene
  • Do you want your operations to continue when the application is minimized or what? - Nikotin N
  • Yes, I need to continue all operations when minimized until I close the application. - Eugene
  • Yes, then you definitely need a service. Well, in the activation to take data for display from the service. - Nikotin N

1 answer 1

To do this, use the Service . Good article in Russian - Service

Service works without a UI in the background of the application (in a separate thread and, if necessary, even a process) and exists just for long-term tasks, which are done without user intervention.

Service has a much lower risk of being closed due to lack of resources. But, even if the service closes, it will be restarted when resources are released (for this I have special flags).

Also, for the Service, the startForegroound () method can be called, which practically excludes the possibility of closing the service if there are not enough resources.