我有一个从一开始就一直在移动的球。我想在按钮单击时停止球。当我单击按钮时,它显示 Toast,但球继续移动。它不会停止。
请指导我如何在按钮单击时停止球。我的活动代码在那里。
@SuppressLint("HandlerLeak")
public class BounceActivity extends Activity {
private static final int GAME_START = 500;
private static final int GAME_STOP = 600;
Thread myRefreshThread = null;
BounceView myBounceView = null;
int width = 0;
int height = 0;
Handler myGUIUpdateHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case BounceActivity.GAME_START:
myBounceView.invalidate();
break;
case BounceActivity.GAME_STOP:
Log.d("BounceView", "Game state: " + BounceView.game_state);
Toast.makeText(BounceActivity.this, "Game stopped", Toast.LENGTH_SHORT).show();
myRefreshThread = null;
break;
}
super.handleMessage(msg);
}
};
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
this.myBounceView = new BounceView(this, dm.widthPixels, dm.heightPixels);
this.setContentView(myBounceView);
myRefreshThread = new Thread(new RefreshRunner());
myRefreshThread.start();
}
class RefreshRunner implements Runnable {
@Override
public void run() {
while (myRefreshThread != null) {
if(BounceView.game_state == 0) {
Message msg = Message.obtain();
msg.what = BounceActivity.GAME_START;
myGUIUpdateHandler.sendMessage(msg);
} else if (BounceView.game_state == 1) {
Message msg = Message.obtain();
msg.what = BounceActivity.GAME_STOP;
myGUIUpdateHandler.sendMessage(msg);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}}