开发者

Is my way of doing threads in Android correct?

I'm writing a live wallpap开发者_如何学Goer, and I'm forking off two separate threads in my main wallpaper service. One updates, and the other draws. I was under the impression that once you call thread.start(), it took care of everything for you, but after some trial and error, it seems that if I want my update and draw threads to keep running, I have to manually keep calling their run() methods? In other words, instead of calling start() on both threads and forgetting, I have to manually set up a delayed handler event that calls thread.run() on both the update and draw threads every 16 milliseconds. Is this the correct way of having a long running thread?

Also, to kill threads, I'm just setting them to be daemons, then nulling them out. Is this method ok? Most examples I see use some sort of join() / interrupt() in a while loop...I don't understand that one...


  1. No
  2. No

For #1, I believe your threads are terminating. Once the run() method is left, the thread is considered terminated. If you want the thread to run "forever", you need to repeat your actions.

For #2, the thread will continue running even if you lose all references to it. I would suggest a signal or condition to the worker thread, followed by a join() in the main thread.


Like Yann said, if you keep having to restart your thread(s), it means you are probably not looping correctly.

Say your wallpaper just has a ball moving around the screen, this would be a sample run() method:

boolean isAnimating;

public void run() {
  isAnimating = true;
  while(isAnimating) {
     moveBall();
     isAnimating = isWallpaperVisible(); // or whatever conditions apply to not keep animating
  }

}

This way your run method will keep running indefinitely.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜