目标效果:在生命小于0时,出现游戏结束画面,然后画面停顿1.5s后显示弹出框问是继续还是退出。
我在制作工程中出现问题有两:
问题1:java.lang.IllegalMonitorStateException: object not locked by thread before wait():
当时为了让画面停顿,即所在线程wait,代码是这么写,直接
try {
Thread.currentThread().wait(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
所以,代码最后改为:
synchronized (Thread.currentThread()) {
try {
Thread.currentThread().wait(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
效果达到,修改成功。
问题2:Can't create handler inside thread that has not called Looper.prepare():
new AlertDialog.Builder(RaidenView.this.getContext())
.setTitle("游戏结束")
.setMessage("你的得分是: " + score + "。")
.setPositiveButton("再来一次", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Intent intent = new Intent("com.example.raiden2.RaidenViewActivity");
// startActivity(intent);
// RaidenViewActivity ractivity = (RaidenViewActivity) RaidenView.this.getContext();
handler.sendMessage(new Message());
}
}).setNegativeButton("退出游戏", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
RaidenViewActivity.this.finish();
}
}).show();
然后就不出所料地报错了- -,这个问题显而易见,也是比较常犯的错误:更新UI是要主线程来更新,即UI线程更新。
最多支持的回答:
所以,最后代码就改为:
RaidenViewActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() { //对话框显示,如上
}}
效果达到,修改成功。
其实,
除了用runOnUiThread还可以使用handler,具体可见:
http://www.2cto.com/kf/201302/190591.html
谢谢大家观看,欢迎对上述代码提出批评。
全部最终代码:
void drawEndImg() {
if(lives.size()==0) {
Rect rect1 = new Rect(0, 0, endImg.getWidth(), endImg.getHeight());
Rect rect2 = new Rect(0, 0, cxf_width, cxf_height);
cxf_thread = false;
mSensorMgr.unregisterListener(this);
canvas.drawBitmap(endImg, rect1, rect2, null);
synchronized (Thread.currentThread()) {
try {
Thread.currentThread().wait(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
RaidenViewActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
synchronized (Thread.currentThread()) {
try {
Thread.currentThread().wait(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
new AlertDialog.Builder(RaidenView.this.getContext())
.setTitle("游戏结束")
.setMessage("你的得分是: " + score + "。")
.setPositiveButton("再来一次", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Intent intent = new Intent("com.example.raiden2.RaidenViewActivity");
// startActivity(intent);
// RaidenViewActivity ractivity = (RaidenViewActivity) RaidenView.this.getContext();
handler.sendMessage(new Message());
}
}).setNegativeButton("退出游戏", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
RaidenViewActivity.this.finish();
}
}).show();
}
});
}
}