Java – Send http requests in android in the application’s onStop

Send http requests in android in the application’s onStop… here is a solution to the problem.

Send http requests in android in the application’s onStop

I have some stats that need to be sent from my Android 4.2+ app to my server and waiting for a response. In fact, some users only run it once, so in order to get data from them, I need to send it in the onStop of the main activity.

As far as I know, requests have to be synchronous: if I create an http worker here, android will continue to run and close the app before executing the http request.
Assuming only one launch can be made, I can’t expect to check the data at the next launch.
I’ve even considered starting the service in onStop (to ensure that the code will execute after the application stops) to handle this request, but it looks ugly.

How did you do that?

Solution

I recommend using IntentService or WakeFullIntentService, you can trigger your work in onStop.

if I create http working thread here android will just run further and close app before http request performed.

No, Android doesn’t terminate your app process immediately, you can start the service and it will do its job. In fact, the system may terminate your apps, but you have to open other heavy apps immediately – like camera, etc.

To avoid you can get your service front desk, by adding a notification

Related Problems and Solutions