Activity code:
public class MainActivity extends Activity { private MyThread myThread; private Handler handler; //The child thread communicates with the UI main thread @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate (savedInstanceState); setContentView(R.layout.main); //Get the message pushed by the child thread through the Handler handler = new Handler () { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle bundle = msg.getData(); String value = bundle.getString("value"); outputEditText.setText(value); } }; // start a child thread myThread = new MyThread(handler); myThread.start(); showDialog("Socket Thread Started!"); } /** * Dialog display */ private void showDialog(String msg){ new AlertDialog.Builder(this) .setTitle("Title") .setMessage(msg) .setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } }
Thread code:
public class MyThread extends Thread{ private Handler handler; public MyThread(Handler handler){ this.handler = handler; } @Override public void run() { try { //Continuously send the current date and time to the UI main thread while(true){ TimeUnit.MILLISECONDS.sleep(1000); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = sdf.format(new Date()); sendMessage(date); } } catch (Exception e) { e.printStackTrace (); } } /** * Send a message to the UI main thread */ private void sendMessage(String msg){ Bundle data = new Bundle(); data.putString("value", msg); Message message = new Message(); message.setData(data); this.handler.sendMessage(message); } }
Handle instantiation when UI needs to be refreshed:
In the main thread: Handler handler = new Handler();
In other thread: Handler handler = new Handler(Looper.getMainLooper());
Handle instantiation without refreshing the UI:
In the main thread: Handler handler = new Handler();
In other threads:
Looper.prepare();
Handler handler = new Handler ();
Looper.loop();
or
Handler handler = new Handler(Looper.getMainLooper());
message.what is generally used to distinguish messages. SetData(Bundle) can be used to transfer data within the process, and message.obj can be used to transfer serializable object data between processes