0

I have android application with several services. This application should send reports to remote server when this application has been started and when has been stopped. But I don't know how to determine that application was stopped, because application may be stopped (crushed for example), but services still running. I think that the algorithm should be like this:

  1. Check the mark with last date from storage (and if this mark exists - send "stop" time to the server)
  2. Send "start" message to the server, when application was started
  3. Every 10 minutes application should writes current date and time mark on disk

If I will create service with this check - android can kill this single service when there is low memory, but application can be running. If I will create ScheduledExecutorService in Application class - application can stop, but services can be still running.

Can you help me with solution?

2 Answers2

0

Why not try to trust standard methods Activity? enter image description here

You should approach onDestroy and / or onPause. It depends on your logic.

In addition, you can try to override Application.onTerminate(). You can read about it (Application) lifecycle here.

Community
  • 1
  • 1
user2413972
  • 1,355
  • 2
  • 9
  • 25
  • Wait. Let's imagine that application has 10 activities, and when I open second activity - first activity can be destroyed, but whole application still running – Alexander Pronin Sep 17 '15 at 17:26
  • Firstly, remained (Application.onTerminate()). Second, you can control the amount of "live" activity. – user2413972 Sep 17 '15 at 17:31
0

There's really not a single answer to this question. It has been asked many, many times here at SO, but all we can say is it really depends on our app's behavior.

You want to put some Log messages in onPause(), onStop(), onDestroy() in your Activity, and onDestroy() in your Service. Watch the the flow of the app carefully by looking at the Log printed out in the Logcat.

Lots of people try to rely on onDestroy() method because it looks like it is called when the app is completely terminated, but that's not always the case. Sometimes app crashes (force closes) or some people just manually force close it in the app information in settings. In that case, app does not follow the lifecycle of the activities.

One of the suggestions would be creating a thread that runs in background and send a UDP packet to a server saying that the app is alive in every few seconds.

PRO: You don't need to make a handshake with the server so it saves time/resources getting response back from the server.

CON: Thread running background does use battery. UDP can be only used in WiFi environment for recent Android OS.

Hope you find a good way. You may want to comment to your post when you found a good solution, because people would like to know how to solve it, too.

Saehun Sean Oh
  • 2,103
  • 1
  • 21
  • 41