package com.example.handlernestdemo; import android.support.v7.app.ActionBarActivity; import android.annotation.SuppressLint; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.Toast; @SuppressLint("HandlerLeak") public class MainActivity extends ActionBarActivity { private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: Message msg1 = obtainMessage(); msg1.what = 1; // myHandler再次发送 myHandler.sendMessage(msg1); break; default: break; } super.handleMessage(msg); } }; private Handler myHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: Toast.makeText(getApplicationContext(), "嵌套实现了。", Toast.LENGTH_LONG).show(); break; default: break; } super.handleMessage(msg); } }; private Button button1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Message message = new Message(); message.what = 1; // mHandler按钮发送一个message mHandler.sendMessage(message); } }); } }