[MyHandlerTest]

|

MyHandlerTest.java
package net.itisn.com;

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

public class MyHandlerTest extends Activity {
	TextView increaseText;
	TextView decreaseText;
	Button startButton;
	
	/** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        increaseText = (TextView)this.findViewById(R.id.increase);
        decreaseText = (TextView)this.findViewById(R.id.decrease);
        startButton = (Button)this.findViewById(R.id.start);
        
        increaseText.setTextSize(30);
        decreaseText.setTextSize(30);
        startButton.setTextSize(30);
        
        startButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				new Thread(new IncreaseThread(updateHandler)).start();
		        new Thread(new DecreaseThread(updateHandler)).start();
			}
		});
    }
	
	class IncreaseThread extends Thread {
		Handler updateHandler;
		int increaseValue = 0;
		
		public IncreaseThread(Handler updateHandler) {
			this.updateHandler = updateHandler;
		}
		
		public void run() {
			// TODO Auto-generated method stub
			while (true) {
				increaseValue++;
				Message msg = Message.obtain();
				msg.what = 0;
				msg.arg1 = increaseValue;
				updateHandler.sendMessage(msg);
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	class DecreaseThread extends Thread {
		Handler updateHandler;
		int decreaseValue = 100;
		
		public DecreaseThread(Handler updateHandler) {
			this.updateHandler = updateHandler;
		}
		
		public void run() {
			// TODO Auto-generated method stub
			while (true) {
				decreaseValue--;
				Message msg = Message.obtain();
				msg.what = 1;
				msg.arg1 = decreaseValue;
				updateHandler.sendMessage(msg);
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	Handler updateHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			if (msg.what == 0) {
				increaseText.setText("Increase : " + msg.arg1);
			} else if (msg.what == 1) {
				decreaseText.setText("Decrease : " + msg.arg1);
			}
		}
		
	};
}


-

'Android' 카테고리의 다른 글

[CustomAdapter]  (0) 2010.09.30
[ImageButton, Toast]  (0) 2010.08.23
[AlertDialog2]  (0) 2010.08.19
[AlertDialog]  (0) 2010.08.18
[MenuTest]  (0) 2010.08.18
And