Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Thread + Handler 實戰:打地鼠小遊戲

編輯:關於 Android 程式設計

Thread 結合 Handler 是 Android 中實現定時更新界面的經典組合。下面用一個「打地鼠」的小遊戲來演示:後台線程隨機計算地鼠出現的位置,通過 Handler 把消息發給主線程更新界面,點擊地鼠後計數並讓它消失。

直接上代碼:

 package com.mingrisoft; import java.util.Random; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; import android.widget.Toast; public class MainActivity extends Activity { private int i = 0; private ImageView mouse; private Handler handler; public int[][] position = new int[][] { { 231, 325 }, { 424, 349 }, { 521, 256 }, { 543, 296 }, { 719, 245 }, { 832, 292 }, { 772, 358 } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mouse = (ImageView) findViewById(R.id.imageView1); mouse.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { v.setVisibility(View.INVISIBLE); i++; Toast.makeText(MainActivity.this, "打到[" + i + "]只地鼠!", Toast.LENGTH_SHORT).show(); return false; } }); handler = new Handler() { @Override public void handleMessage(Message msg) { int index = 0; if (msg.what == 0x101) { index = msg.arg1; mouse.setX(position[index][0]); mouse.setY(position[index][1]); mouse.setVisibility(View.VISIBLE); } super.handleMessage(msg); } }; Thread t = new Thread(new Runnable() { @Override public void run() { int index = 0; while (!Thread.currentThread().isInterrupted()) { index = new Random().nextInt(position.length); Message m = handler.obtainMessage(); m.what = 0x101; m.arg1 = index; handler.sendMessage(m); try { Thread.sleep(new Random().nextInt(500) + 500); } catch (InterruptedException e) { e.printStackTrace(); } } } }); t.start(); } }

配套的布局文件:

  

關鍵點在於:線程不能直接操作 UI,所以地鼠位置的更新必須通過 Handler 發送 Message 交給主線程處理。利用 Message 的 arg1 字段攜帶位置索引,就能把後台計算的結果準確地傳遞到界面刷新邏輯中。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved