start thread and communicate with it
[UdpRespond.git] / src / com / example / udpresponder / UdpRespondActivity.java
index b0e54ea607d7736f3546bf3de8a321bd57dc04df..7ef9709749f9909b2b3d7be5bf2ae562f7c5b0a1 100644 (file)
@@ -2,14 +2,68 @@ package com.example.udpresponder;
 
 import android.app.Activity;
 import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.os.SystemClock;
+import android.widget.TextView;
+import android.widget.Button;
+import android.view.View;
+import android.view.View.OnClickListener;
 
-public class UdpRespondActivity extends Activity
-{
-    /** Called when the activity is first created. */
-    @Override
-    public void onCreate(Bundle savedInstanceState)
-    {
-        super.onCreate(savedInstanceState);
-        setContentView(R.layout.main);
-    }
+public class UdpRespondActivity extends Activity {
+
+       private Handler mHandler = new Handler() {
+               public void handleMessage(Message msg) {
+                       Bundle bdl = msg.getData();
+                       updateUI(bdl.getString("ln"));
+               }
+       };
+
+       private TextView tv;
+
+       private OnClickListener mStartListener = new OnClickListener() {
+               public void onClick(View v) {
+                       tv.append("Start pressed\n");
+               }
+       };
+
+       private OnClickListener mStopListener = new OnClickListener() {
+               public void onClick(View v) {
+                       tv.append("Stop pressed\n");
+                       finish();
+               }
+       };
+
+       @Override
+       public void onCreate(Bundle savedInstanceState) {
+               super.onCreate(savedInstanceState);
+               setContentView(R.layout.main);
+               tv = (TextView)findViewById(R.id.tv);
+               tv.append(" Starting\n");
+               Button btn_start = (Button)findViewById(R.id.btn_start);
+               btn_start.setOnClickListener(mStartListener);
+               Button btn_stop = (Button)findViewById(R.id.btn_stop);
+               btn_stop.setOnClickListener(mStopListener);
+               startBgThread();
+       }
+
+       private void updateUI(String str) {
+               tv.append(str);
+       }
+
+       protected void startBgThread () {
+               Thread t = new Thread() {
+                       public void run() {
+                               while (true) {
+                                       SystemClock.sleep(3000);
+                                       Bundle bdl = new Bundle();
+                                       bdl.putString("ln", "this is msg\n");
+                                       Message msg = Message.obtain(mHandler);
+                                       msg.setData(bdl);
+                                       msg.sendToTarget();
+                               }
+                       }
+               };
+               t.start();
+       }
 }