Android:如何停止Runnable?

我试过这种方式:

private Runnable changeColor = new Runnable() { private boolean killMe=false; public void run() { //some work if(!killMe) color_changer.postDelayed(changeColor, 150); } public void kill(){ killMe=true; } }; 

但是我不能访问kill()方法!

而是使用SDK提供的现有API来实现您自己的thread.kill()机制。 在一个线程池中pipe理你的线程创build,并使用Future.cancel()来终止正在运行的线程:

 ExecutorService threadPoolExecutor = Executors.newSingleThreadExecutor(); Runnable longRunningTask = new Runnable(); // submit task to threadpool: Future longRunningTaskFuture = threadPoolExecutor.submit(longRunningTask); ... ... // At some point in the future, if you want to kill the task: longRunningTaskFuture.cancel(true); ... ... 

根据您的任务运行状态,取消方法的performance会有所不同,请查看API获取更多详细信息。

 public abstract class StoppableRunnable implements Runnable { private volatile boolean mIsStopped = false; public abstract void stoppableRun(); public void run() { setStopped(false); while(!mIsStopped) { stoppableRun(); stop(); } } public boolean isStopped() { return mIsStopped; } private void setStopped(boolean isStop) { if (mIsStopped != isStop) mIsStopped = isStop; } public void stop() { setStopped(true); } } 

class……

  private Handler mHandler = new Handler(); public void onStopThread() { mTask.stop(); mHandler.removeCallbacks(mTask); } public void onStartThread(long delayMillis) { mHandler.postDelayed(mTask, delayMillis); } private StoppableRunnable mTask = new StoppableRunnable() { public void stoppableRun() { ..... onStartThread(1000); } } }; 
 mHandler.removeCallbacks(updateThread); 

changeColor声明为Runnable ,它没有kill()方法。

您需要创build自己的扩展Runnable的接口并添加一个(public) kill()方法。