본문 바로가기

Android/Thread

안드로이드/Android Thread 사용하기~!

안드로이드/Android Thread 사용하기~!

 
package arabiannight.tistory.com;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;

public class TestThreadActivity extends Activity {

	private Handler mHandler;
	private TextView mTvNumber;
	private NumberThread mNumberThread;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mTvNumber = (TextView) findViewById(R.id.tv_number);
		mHandler = new Handler();

	}

	public void onButtonClick(View v){
		switch (v.getId()) {
		case R.id.btn_start:
			mNumberThread = new NumberThread(true);
			mNumberThread.start();
			break;
		case R.id.btn_stop:
			mNumberThread.stopThread();
//			if( mNumberThread != null && mNumberThread.isAlive() ){
//				mNumberThread.interrupt();
//			}
			break;
		}
	}

	class NumberThread extends Thread {

		private int i = 0;
		private boolean isPlay = false;

		public NumberThread(boolean isPlay){
			this.isPlay = isPlay;
		}

		public void stopThread(){
			isPlay = !isPlay;
		}
		@Override
		public void run() {
			super.run();
			while (isPlay) {
				try { Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						mTvNumber.setText(""+i++);
					}
				});
			}
		}
	}
}