我试图做的是每次计数器变为5的倍数时减少定时器延迟.
但是,一旦代码进入if块,它就会停止递增计时器.
我无法理解发生了什么.
但是,一旦代码进入if块,它就会停止递增计时器.
我无法理解发生了什么.
这是代码
thread=new Thread(){
public void run(){
try{
if(count%5==0)
timre--;
else{
//do nothing
}
//*******PROGRESS UPDATE********//
for(t=0;t<=100;t++) {
sleep((timre) / 100);
progress.setProgress(t);
t += 1;
}
//****PROGRESS UPDATE OVER****//
} catch (InterruptedException e) {
e.printstacktrace();
}
finally {
finish();
}
}//run ends
};//thread ends
thread.start();//timer starts
解决方法
Thread.sleep()不保证.这意味着它可能会或可能不会因您出于此问题的主题之外的各种原因而在您期望的时间内睡眠.
如果你在网上搜索“android中的计时器”,你可能会登陆这两个:https://developer.android.com/reference/java/util/Timer.html和https://developer.android.com/reference/java/util/concurrent/ScheduledThreadPoolExecutor.html
您可以检查它们,但是,我不会使用它们,因为它们提供了许多其他功能,如名称所示(“ScheduledThreadPoolExecutor”).你不需要这个,因为这很可能被用于拥有大量线程等的大型系统……
如果我正确理解您的代码,您正在尝试更新进度条.
对于你想要做的事情,我建议使用一个处理程序.处理程序的主要用途之一是将消息和可运行程序安排为将来执行的某个点,如此处的文档中所指定的:
http://developer.android.com/reference/android/os/Handler.html
我会这样做:
int counter = 0;
int delayInMs = 5000; // 5 seconds
Handler timer = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
counter++;
// If the counter is mod 5 (or whatever) lower the delay
if (counter % 5 == 0) {
delayInMs/=100; // Or any other calculation.
}
// If the counter reaches 100 the counting will not continue.
if (counter <= 100) {
// If the counter has not reached the condition to stop,the handler
// will call the timer again with the modified (or not) delay.
timer.sendEmptyMessageDelayed(0,delayInMs);
// Change progress
updateProgress(counter);
}
return true;
}
});
// ...
// Somwhere in the code to start the counter
timer.sendEmptyMessageDelayed(0,delayInMs); // starts the timer with the initial 5 sec delay.
还有一件事.在您拥有此代码的行中:
progress.setProgress(t);
从其他线程调用UI元素时要小心,这是很多头痛的根源.如果你的处理程序在另一个线程中,你应该将该调用包装在一个函数中,并确保从主线程(即UI线程)调用它.实现这一目标的许多方法(并非总是必要的).其中一个是这样的:
private void updateProgress(int counter) {
WhateverActivity.this.runOnUiThread(new Runnable() {
public void run() {
progress.setProgress(counter);
}
});
}