Android development Thread + Handler example (hamster)
Directly Add code
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; // records the number of hamster private ImageVi Ew mouse; // declare an ImageView object private Handler handler; // declare a Handler object public int [] [] position = new int [] [] {231,325 }, {424,349 },{ 521,256 },{ 543,296 },{ 719,245 },{ 832,292 },{ 772,358 }}; // create an array @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); mouse = (ImageView) findViewById (R. id. imageView1 );// Obtain the ImageView object mouse. setOnTouchListener (new OnTouchListener () {@ Overridepublic boolean onTouch (View v, MotionEvent event) {v. setVisibility (View. INVISIBLE); // set the mouse to not display I ++; Toast. makeText (MainActivity. this: Hit the [+ I +] hamster !, Toast. LENGTH_SHORT ). show (); // display the Message prompt box return false ;}}); handler = new Handler () {@ Overridepublic void handleMessage (Message msg) {int index = 0; if (msg. what = 0x101) {index = msg. arg1; // obtain the location index value mouse. setX (position [index] [0]); // you can specify the x-axis position for mouse. setY (position [index] [1]); // you can specify the Y axis for mouse. setVisibility (View. VISIBLE); // set the mouse display} super. handleMessage (msg) ;}}; Thread t = new Thread (new Runnable () {@ Overridepubl Ic void run () {int index = 0; // create an index that records the location of the hamster while (! Thread. currentThread (). isInterrupted () {index = new Random (). nextInt (position. length); // generate a random number Message m = handler. obtainMessage (); // get a Messagem. what = 0x101; // sets the Message ID m. arg1 = index; // Save the index value handler at the location of the cursor. sendMessage (m); // send the message try {Thread. sleep (new Random (). nextInt (500) + 500); // sleep for a period of time} catch (InterruptedException e) {e. printStackTrace () ;}}}); t. start (); // enable thread }}
<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>