0

I want to run a network request once user closes an app i.e. onStop and onDestroy is called on app's activity. The problem is I also want to wait for response from server and save some data locally after I get it so the whole procedure may need to be finished after the app is fully closed.

Is there any kind of background service in Android which won't be terminated after app is closed and will be waiting for requests's completion (for some reasonable time at least)?

src091
  • 2,807
  • 7
  • 44
  • 74
  • 1
    Yes. Look [here](https://developer.android.com/training/run-background-service/create-service.html). The real catch though is determining the right time you consider your application is closing. – Ahmed Khalaf Jul 22 '16 at 16:22
  • you can start a service while user close the app. Inside that service try to handle what you need to do. – Atahar Hossain Jul 22 '16 at 16:39
  • @AhmedKhalaf this looks good. Can you please elaborate on why determining the right time might be a problem? Can't I just start such a service in `onDestroy`? – src091 Jul 23 '16 at 05:22
  • 1
    You can. But which activity will be the last shown activity when the app is about to close?. Moreover, what is your definition of closing? Is it when the user presses back till he's out of the app (the app can still be running) ? Or when the app process is terminated? – Ahmed Khalaf Jul 23 '16 at 11:12

1 Answers1

0

The solution is Non UI fragment. Here is an example I have created: https://github.com/kadymuhammad/Non-UI-Fragment . You can also see this answer https://stackoverflow.com/a/21336010/5186466 Using Asynctask inside a Non UI fragment will continue to run even if the activity is paused but i will stop if the app task stopped. The perfect solution is to use Service or IntentService classes. Check this out : http://www.tutorialspoint.com/android/android_services.htm

Community
  • 1
  • 1