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 } }; //
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mouse = (ImageView) findViewById(R.id.imageView1); // ImageView
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]); // X
mouse.setY(position[index][1]); // Y
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(); // Message
m.what = 0x101; //
m.arg1 = index; //
handler.sendMessage(m); //
try {
Thread.sleep(new Random().nextInt(500) + 500); //
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start(); //
}
}
レイアウトファイル:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fl"
android:background="@drawable/background"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/mouse" />
</FrameLayout>