先上段代碼吧java
package com.example.handlerdemo; import android.app.Activity; import android.content.res.Resources.Theme; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity implements OnClickListener { myHandler mHandler; private Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn = (Button) findViewById(R.id.button1); btn.setOnClickListener(this); // 【1】當建立一個新的Handler實例時, 它會綁定到當前線程和消息的隊列中,開始分發數據 // [2]Handler有兩個做用 // <1>定時執行Message和Runnalbe 對象 // <2>讓一個動做,在不一樣的線程中執行 mHandler = new myHandler(); } /** * 接受消息,處理消息 ,此Handler會與當前主線程一塊運行 * * @author huangc 繼承Handler類而且重寫handleMessage方法 * * 子類須要繼承Handler類,並重寫handleMessage(Message msg) 方法, 用於接受線程數據 */ class myHandler extends Handler { public myHandler() { super(); // TODO Auto-generated constructor stub } @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); Log.e("huangc", " handleMessage!!! "); Bundle b = msg.getData(); Log.e("huangc", "MSG get!!!!=" + b.get("MSG")); } } /** * @author huangc 在Android UI主線程外寫一個單獨的線程 */ class MyThread implements Runnable { @Override public void run() { // TODO Auto-generated method stub Log.e("huangc", " Runnable!!! "); try { Thread.sleep(1000); } catch (Exception e) { // TODO: handle exception } Message msg = new Message(); Bundle b = new Bundle(); b.putString("MSG", "OK"); msg.setData(b); // 該線程在執行過程當中向handler發送消息 MainActivity.this.mHandler.sendMessage(msg); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(View arg0) { // TODO Auto-generated method stub int id = arg0.getId(); if (id == R.id.button1) { // 【2】新起一個線程,跑起來 MyThread mThread = new MyThread(); new Thread(mThread).start(); } } }