Jac*_*jjc 0 multithreading android view
我正在做一个15拼图(http://en.wikipedia.org/wiki/Fifteen_puzzle)游戏,我有一个活动供用户选择背景图像,然后我将该图像传递给一个新的活动,以便缩放并裁剪它.
现在我想首先向用户显示解决方案3秒然后它会随机播放,我使用的代码如下:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//...skip the code that gets the image and scales it
start();
}
Run Code Online (Sandbox Code Playgroud)
然后在我的start()函数中:
public void start() {
//the createPuzzle function would create all the Views(tiles)
//and add them to the root LinearLayout using addView() function
createPuzzle(game.getBoardConfig(), dimension);
//i was trying to sleep here
shuffle();
}
Run Code Online (Sandbox Code Playgroud)
我用了:
try {
Thread.sleep(3000);
} catch (InterruptedException e) {}
Run Code Online (Sandbox Code Playgroud)
要么:
SystemClock.sleep(3000);
Run Code Online (Sandbox Code Playgroud)
但是他们都没有正常工作,他们在我选择图像后立即暂停了线程,当它暂停时我看不到新活动和我创建的图块.当线程恢复时,它已经显示了混乱的拼图.
我一直在查看文档很长一段时间,但仍然无法弄清楚我的代码有什么问题,谢谢你的帮助!
不要让UI线程休眠,因为这将锁定整个UI线程,这是禁忌.相反,使用Handler发布延迟的runnable ...就像
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
shuffle();
}
}, 3000);
Run Code Online (Sandbox Code Playgroud)