0

I have an activity which has a class which extends SurfaceView and implements Runnable to constantly draw on a Canvas object. I realized when I want to switch activity and kill the current one, the Thread will not be destroyed by itself even if I call finish(). Thus, I would like to know when is the best time to destroy that thread (probably in onDestroy() method?) and more importantly how to destroy that thread? Thank you.

TheEngineer
  • 792
  • 6
  • 18
  • Re, "...implements Runnable to constantly draw on a Canvas object..." I don't know Android specifically, but in most GUI frameworks, the best, most general way to _animate_ a display is to set up a periodic `Timer` task to update the display at regular intervals. – Solomon Slow Mar 11 '18 at 19:13
  • @jameslarge Thank you for your comment, in Android it is standard to have a separate thread for 2-D Animations which constantly draws on a Canvas Object – TheEngineer Mar 14 '18 at 05:11

1 Answers1

1

No, because onDestroy isnt always called when the activity ends. the best thing to do would be is onStop() you kill the thread, and in onStart() you always start it up.

that way the thread will never be running while your activity is in the background and will be killed when it is closed.

To kill a thread depends on what kind of thread you are using. a regular thread can be killed with

yourThread.interrupt()

then in your thread you would do something like

while(!Thread.currentThread().isInterrupted()) {
         // ...
    }
Tomer Shemesh
  • 10,278
  • 4
  • 21
  • 44