0

I would like to run an async task when the app is closed out and only then. I tried putting it in the onDestroy() method but it only gets called sometimes (such as when the app is crashed). I also tried to put it on the onPause() method, but it also runs when the user tries to look at a different app rather than only when the app closes. Thanks!

Sincerely, Rocky

Rockyfish
  • 339
  • 3
  • 15
  • duplicate of http://stackoverflow.com/questions/5593115/run-code-when-android-app-is-closed-sent-to-background and http://stackoverflow.com/questions/5747803/running-code-on-program-exit-in-java and http://stackoverflow.com/questions/18827085/run-service-even-if-the-application-is-closed-killed –  Feb 24 '16 at 06:32
  • Tried calling `finish()` on `onBackPressed()` and checked `onDestroy()` getting called? – Viswanath Lekshmanan Feb 24 '16 at 06:32
  • use service to run in background .. – priyanka morisetti Feb 24 '16 at 06:32
  • i think this will give you a good idea http://developer.android.com/reference/android/os/AsyncTask.html – Sree Feb 24 '16 at 06:40

1 Answers1

2

You should use Thread instead of AsyncTask, but if you want to use AsyncTask you'll need to do the following:

  1. Don't update the UI in AsyncTask because onDestroy removes the resources and context for that activity. It will crash if you try to update them.

  2. Use the application Context not the activity Context when you create your AsyncTask, because the activity Context is invalid after the activity is destroyed.

smunk
  • 314
  • 3
  • 8