Android開發之Thread+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; // 聲明一個ImageView對象private Handler handler; // 聲明一個Handler對象public int[][] position = new int[][] { { 231, 325 }, { 424, 349 },{ 521, 256 }, { 543, 296 }, { 719, 245 }, { 832, 292 },{ 772, 358 } }; // 建立一個表示地鼠位置的數組@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);mouse = (ImageView) findViewById(R.id.imageView1); // 擷取ImageView對象mouse.setOnTouchListener(new OnTouchListener() {@Overridepublic 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() {@Overridepublic void handleMessage(Message msg) {int index = 0;if (msg.what == 0x101) {index = msg.arg1; // 擷取位置索引值mouse.setX(position[index][0]); // 設定X軸位置mouse.setY(position[index][1]); // 設定Y軸位置mouse.setVisibility(View.VISIBLE); // 設定地鼠顯示}super.handleMessage(msg);}};Thread t = new Thread(new Runnable() {@Overridepublic void run() {int index = 0; // 建立一個記錄地鼠位置的索引值while (!Thread.currentThread().isInterrupted()) {index = new Random().nextInt(position.length); // 產生一個隨機數Message m = handler.obtainMessage(); // 擷取一個Messagem.what = 0x101; // 設定訊息標識m.arg1 = index; // 儲存地滑鼠位置的索引值handler.sendMessage(m); // 發送訊息try {Thread.sleep(new Random().nextInt(500) + 500); // 休眠一段時間} catch (InterruptedException e) {e.printStackTrace();}}}});t.start(); // 開啟線程}}
<framelayout android:background="@drawable/background" android:id="@+id/fl" android:layout_height="fill_parent" android:layout_width="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"> </framelayout>