Thread.sleep() non è garantito. Ciò significa che può o non può dormire per la durata desiderata per vari motivi fuori tema per questa domanda.
Se si cerca la rete per "timer in Android" si avrà probabilmente atterrare su questi due: https://developer.android.com/reference/java/util/Timer.html e https://developer.android.com/reference/java/util/concurrent/ScheduledThreadPoolExecutor.html
Si potrebbe controllare fuori, però, non vorrei usare quelli in quanto forniscono un sacco di altre funzionalità come suggerisce il nome ("ScheduledThreadPoolExecutor"). Non hai bisogno di questo perché è più probabile che venga utilizzato per grandi sistemi con molti thread ecc ...
Se ho capito bene il tuo codice, stai tentando di aggiornare una barra di avanzamento. Per quello che stai cercando di fare ti suggerirei di usare un gestore.Uno dei principali usi di un gestore è quello di pianificare i messaggi e runnables essere eseguito come un certo punto in futuro, come specificato nella documentazione qui: http://developer.android.com/reference/android/os/Handler.html
lo farei in questo modo:
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.
Un'altra cosa. Nella riga in cui si dispone di questo codice:
progress.setProgress(t);
Fare attenzione quando si chiama elementi dell'interfaccia utente da altri thread è la fonte di molti mal di testa. Se il tuo gestore si trova in un altro thread, dovresti racchiudere quella chiamata in una funzione e assicurarti che sia chiamata dal thread principale (cioè il thread dell'interfaccia utente). Molti modi per ottenere ciò (non sempre necessario). Uno di loro è in questo modo:
private void updateProgress(int counter) {
WhateverActivity.this.runOnUiThread(new Runnable() {
public void run() {
progress.setProgress(counter);
}
});
}
fonte
2015-06-23 13:01:24
Puoi mostrare più codice per favore? Dove inizializzi il timer? – Wishmaster