1. package com.nguyenmp.ErrorTest;
  2.  
  3. import android.app.Activity;
  4. import android.app.AlertDialog;
  5. import android.app.Dialog;
  6. import android.content.Context;
  7. import android.os.Bundle;
  8. import android.os.Handler;
  9. import android.os.Looper;
  10. import android.os.Message;
  11. import android.view.View;
  12. import android.widget.Button;
  13. import android.widget.Toast;
  14.  
  15. public class MyActivity extends Activity {
  16.  
  17.     @Override
  18.     public void onCreate(Bundle savedInstanceState) {
  19.         super.onCreate(savedInstanceState);
  20.  
  21.         //Init the UI
  22.         setContentView(R.layout.main);
  23.  
  24.         //Create a new handler, passing it the current activity context
  25.         final Handler handler = new MyHandler(MyActivity.this);
  26.  
  27.         //Bind a listener to the button on the UI
  28.         View view = findViewById(R.id.button);
  29.         view.setOnClickListener(new View.OnClickListener() {
  30.  
  31.             @Override
  32.             public void onClick(View v) {
  33.                 //Start a new thread that will send a message to that handler
  34.                 new MyThread(handler).start();
  35.             }
  36.  
  37.         });
  38.     }
  39.  
  40.     private class MyThread extends Thread {
  41.         private final Handler mHandler;
  42.  
  43.         MyThread(Handler handler) {
  44.             mHandler = handler;
  45.         }
  46.  
  47.         @Override
  48.         public void run() {
  49.             //Dispatch message to UI thread asynchronously
  50.             Looper.prepare();
  51.             mHandler.dispatchMessage(mHandler.obtainMessage());
  52.         }
  53.     }
  54.  
  55.     private class MyHandler extends Handler {
  56.         private final Context mContext;
  57.  
  58.         MyHandler(Context context) {
  59.             mContext = context;
  60.         }
  61.  
  62.         @Override
  63.         public void handleMessage(Message msg) {
  64.             //Show that we got the message
  65.             AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
  66.             builder.setTitle("HelloWorld");
  67.             builder.setMessage("It worked!");
  68.             builder.show();
  69.  
  70.             //Another variant of showing that we got the message
  71.             Toast.makeText(mContext, "Message Received", Toast.LENGTH_SHORT).show();
  72.  
  73.             System.out.println("Yeah");
  74.         }
  75.     }
  76. }