在Android/Java中,如何在for循环中的迭代之间等待特定的时间?
我正在制作一个程序,在同一个ImageView中显示图像的不同部分。但在任何两次图像更改之间,它都应该等待一段时间,大约500毫秒。 像这样:在Android/Java中,如何在for循环中的迭代之间等待特定的时间?,java,android,for-loop,Java,Android,For Loop,我正在制作一个程序,在同一个ImageView中显示图像的不同部分。但在任何两次图像更改之间,它都应该等待一段时间,大约500毫秒。 像这样: for(int i=1; i<=4;i++){ for(int j=1;j<=4;j++){ //code to refresh the image. // wait for 500 milliseconds before resuming the normal iteration } } for(int i=1;i如果这在
for(int i=1; i<=4;i++){
for(int j=1;j<=4;j++){
//code to refresh the image.
// wait for 500 milliseconds before resuming the normal iteration
}
}
for(int i=1;i如果这在UI线程循环内,则应使用AsyncTask
或计时器来实现目标,以避免阻塞UI
使用AsyncTask
:
class UpdateImages extends AsyncTask<Void, Integer, Boolean> {
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Integer... values) {
// refresh the image here
}
@Override
protected Boolean doInBackground(Void... params) {
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
// NOTE: Cannot call UI methods directly here.
// Call them from onProgressUpdate.
publishProgress(i, j);
try {
Thread.sleep(500);
} catch(InterruptedException) {
return false;
}
}
}
return true;
}
@Override
protected void onPostExecute(Boolean result) {
}
}
当您想启动此任务时。使用AsyncTask
这种方式可以避免阻塞您的UI,并且仍然可以让您按计划执行任何操作。请注意Thread.sleep
抛出InterruptedException
。您应该用try/catch块代码围绕该句。捕捉得好。我知道我忘了什么:)有一个问题,我应该在activity.java类中包含这个类,还是在同一个包中声明它?我没有任何其他应该在后台发生的功能。那么,这段代码会阻止调用其他函数吗???我的意思是,我不希望在映像更改过程中运行任何其他进程。??AsyncTask可以声明为内部类或单独的类。由于这个类处理图像,所以将其作为一个内部类可能更容易,但这取决于您<代码>异步任务
在自己的线程中运行,因此它不会阻止任何其他任务。
class UpdateImages extends AsyncTask<Void, Integer, Boolean> {
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Integer... values) {
// refresh the image here
}
@Override
protected Boolean doInBackground(Void... params) {
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
// NOTE: Cannot call UI methods directly here.
// Call them from onProgressUpdate.
publishProgress(i, j);
try {
Thread.sleep(500);
} catch(InterruptedException) {
return false;
}
}
}
return true;
}
@Override
protected void onPostExecute(Boolean result) {
}
}
new UpdateImages().execute();