A thread in my View component: when to stop the thread?
I created a View component for android. The component has its own thread to make backg开发者_高级运维round work. I start the thread in the View constructor. Where should I stop the thread? Is onDetachedFromWindow a correct place to make it?
I would do it the following way provided the Thread
has to be active during the time the View
has a Surface
and uses it for drawing:
public class MyView extends View {
class MyThread extends Thread {
private boolean mActive = true;
public void run() {
while (mActive) {
doThings();
}
}
public void terminate() {
mActive = false;
}
private void doThings() {
// the things your thread should do
}
}
private MyThread mBackgroundOperation = null;
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mBackgroundOperation = new MyThread();
mBackgroundOperation.start();
}
protected void onDetachedFromWindow() {
mBackgroundOperation.terminate();
mBackgroundOperation = null;
super.onDetachedFromWindow();
}
}
If this is not the case (if the Thread
's lifecycle is not directly dependant of the use of the View
's Surface
for drawing) I would think twice about handling it inside the View
, and would maybe consider moving it to the Activity
that uses this View
instead. "Maybe" because this is a difficult thing to determine without knowing what this Thread
actually does.
stop() method is deprecated
. Check this:
http://developer.android.com/reference/java/lang/Thread.html#stop%28java.lang.Throwable%29
you should get your work done and leave it, Android is smart enough to take care of it..
The best time to stop a view updating is probably when it's no longer visible. Your activity's onStop() method will be called when this happens, and from there you could call a method you write in your custom view to shutdown its update thread.
// Activity.java
public void onStop() {
myThreadedView.shutdown();
... // rest of onStop() here
}
// ThreadedView.java
public void shutdown() {
myViewThread.shutdown();
}
// ViewThread.java
bool stop = false;
public void shutdown() {
stop = true;
}
public void run() {
while (!stop) {
updateView();
}
}
精彩评论