我正在尝试编写将每5秒执行一次的代码,我读了一些关于延迟的内容,并且似乎使用postDelay方法将帮助我做到这一点,但由于某种原因,这会被执行两次。每隔5秒我得到这个日志,差异大约是500毫秒。如何修改此代码每5秒钟完成一次?
03-09 20:56:25.982 4735-4735/com.example.mdots_000.newprojectwithdelay I/Value: 1
03-09 20:56:26.442 4735-4735/com.example.mdots_000.newprojectwithdelay I/Value: 2
public class MainActivity extends AppCompatActivity {
Handler handler;
Runnable runnable;
int delay = 5000;
int value = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
}
@Override
protected void onResume() {
super.onResume();
handler.postDelayed(new Runnable() {
@Override
public void run() {
runnable = this;
value++;
Log.i("Value", String.valueOf(value));
handler.postDelayed(runnable, delay);
}
}, delay);
}
}