我有一段代码中使用了postDelayed和其他在主线程上执行的代码。我运行了几次,每次都看到以下输出:
07-13 14:22:18.511 15376-15376/sample1.com.sample_1 D/MainActivity: i = 0
....
07-13 14:22:18.601 15376-15376/sample1.com.sample_1 D/MainActivity: onResume 07-13 14:22:18.601 15376-15376/sample1.com.sample_1 D/MainActivity: postDelayed
从日志输出中可以看出,即使我的延迟为50毫秒,也无关紧要。消息“postDelayed”在大约100毫秒后(601-511=90)输入。看起来延迟的可运行程序被添加到了UI线程的消息队列的末尾。但是,是否有保证postDelayed会在什么时候被输入?它可能在for循环的中间被输入吗?
package sample1.com.sample_1;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.d("MainActivity", "postDelayed");
}
}, 10);
for (int i = 0; i < 10000; i++) {
Log.d("MainActivity", "i = " + i);
}
}
@Override
protected void onResume() {
Log.d("MainActivity", "onResume");
super.onResume();
}
}