Android/개발팁

Thread Hanlder 간단하게 쓰기

hoonihoon 2013. 7. 24. 16:08
public class MainActivity extends Activity implements OnClickListener {
	int mMainValue = 0;
	int mBackValue = 0;
	TextView mMainText;
	TextView mBackText;
	Button increase;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mMainText = (TextView)findViewById(R.id.mainvalue);
		mBackText = (TextView)findViewById(R.id.backvalue);
		increase = (Button)findViewById(R.id.increase);

		increase.setOnClickListener(this);

		BackThread thread = new BackThread();
		thread.setDaemon(true);
		thread.start();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		mMainValue++;
		mMainText.setText("MainValue : " + mMainValue);
	}

	class BackThread extends Thread {
		public void run() {
			while (true) {
				mBackValue++;
				mHandler.sendEmptyMessage(0);
				try { Thread.sleep(1000); } catch (InterruptedException e) {;}
			}
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			if(msg.what ==0) {
				mBackText.setText("BackValue : " + mBackValue);
			}
		}
	};
 

}