package com.nguyenmp.ErrorTest; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MyActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Init the UI setContentView(R.layout.main); //Create a new handler, passing it the current activity context final Handler handler = new MyHandler(MyActivity.this); //Bind a listener to the button on the UI View view = findViewById(R.id.button); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Start a new thread that will send a message to that handler new MyThread(handler).start(); } }); } private class MyThread extends Thread { private final Handler mHandler; MyThread(Handler handler) { mHandler = handler; } @Override public void run() { //Dispatch message to UI thread asynchronously Looper.prepare(); mHandler.dispatchMessage(mHandler.obtainMessage()); } } private class MyHandler extends Handler { private final Context mContext; MyHandler(Context context) { mContext = context; } @Override public void handleMessage(Message msg) { //Show that we got the message AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setTitle("HelloWorld"); builder.setMessage("It worked!"); builder.show(); //Another variant of showing that we got the message Toast.makeText(mContext, "Message Received", Toast.LENGTH_SHORT).show(); System.out.println("Yeah"); } } }