package gr.mybook.mythreadmessage;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class Activity_1 extends Activity {
	TextView text;
	//new handler
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
		   // get the bundle and extract data by key
		   Bundle b = msg.getData();
		   String key = b.getString("My Key");
		   text.setText(key);
		}
	};

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_1);
        text = (TextView) findViewById(R.id.textView1);
    }
    
    @Override
    protected void onStart() {
     super.onStart();
    
       // create a new thread
       Runnable runnable = new Runnable() {
           public void run() {
              for (int i = 0; i < 10; i++) {
                 try {
                    Thread.sleep(1000);
                   Message msg = handler.obtainMessage();
                   //Message msg = new Message();
                   Bundle b = new Bundle();
                   b.putString("My Key", "THREAD MESSAGE:  " + String.valueOf(i));
                   msg.setData(b);
                   // send message to the handler with the current message handler
                   handler.sendMessage(msg);
                 } catch (InterruptedException e) {
                 	e.printStackTrace();
                   }

             }
          }
       };
       Thread thread = new Thread(runnable);
       thread.start();
    }
    
   
}