2

How can i finish my TimerTask's after the app was closing? Garbage Collector not working properly or just not want to finish any background task or threads.

pumukel
  • 71
  • 9

2 Answers2

1

Assuming you want to stop it when the Activity is destroyed :

@Override
protected void onDestroy()
{
    super.onDestroy();
    yourTimer.cancel();
}

Or if you want to stop it when your activity is hidden :

@Override
protected void onStop()
{
    super.onStop();
    yourTimer.cancel();
}

According to the activity workflow, choose the best method where your timer has to be cancelled :

enter image description here

ToYonos
  • 16,469
  • 2
  • 54
  • 70
  • Indeed, hard to say when it's called, but eventually it is – ToYonos Oct 24 '14 at 13:59
  • thats exactly the point, i dont want to cancel my background task in an activity method, because it updates periodically the data which are used in different activities. I just want finish my Task when the application is closing... – pumukel Oct 24 '14 at 14:16
  • No way to trigger any action when the application is closing. – ToYonos Oct 24 '14 at 14:18
  • So, its not possible to have background thread which can run behinde different activities and close properly? So i always have to start and stop each time a activity is created and stopped? – pumukel Oct 24 '14 at 14:28
  • You have to manage yourself this thread. What you cannot do is stop it at the same time as your application is killed by Android. You can only bind your thread ending to an activity state or something you can predict. – ToYonos Oct 24 '14 at 14:31
0

You should stop your any thread/task in onDestroy() in your Activity. By the way, you should not use TimerTask in Android. Check this SO question: TimerTask vs Thread.sleep vs Handler postDelayed - most accurate to call function every N milliseconds?

In order to update data you can do that in service (and you should, instead of activity).

Community
  • 1
  • 1
Jakub
  • 1
  • 1