2015年12月11日 星期五

How to stop a thread

Reference:

http://sp-tech.blogspot.tw/2012/11/java-java.html

Code snippet:

public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
        private boolean isRunning = true;
private Thread mThread;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

mThread = new Thread(new MyTask());
                mThread.start();
        }

private class MyTask implements Runnable{

        @Override
        public void run() {
Log.d(TAG,"Thread starts");
            while(isRunning){
try{
//do something
Log.d(TAG,"Sleeping...");
Thread.sleep(5000);
} catch(InterruptedException e){
Log.d(TAG,"Thread was inturrupted");
} catch(Exception e) {
//handle error
e.printStackTrace();
}  
}
Log.d(TAG,"Thread ends");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isRunning = false; // make the thread leave
        mThread.interrupt();
    }
}

沒有留言: