我有這樣的代碼在MainActivity:延遲崩潰的應用程序
boolean running = true;
@Override
public void onClick(View v) {
Button button = (Button)findViewById(R.id.start);
new Thread(new Runnable() {
public void run() {
int secs = 1;
while(running){
Utils.delay(secs, new Utils.DelayCallback() {
int seconds = 0;
TextView licznik = (TextView)findViewById(R.id.licznik);
@Override
public void afterDelay() {
seconds = seconds + 1;
licznik.setText(Integer.toString(seconds));
}
});
}
}
}).start();
}
及其utils的類:
import android.os.Handler;
public class Utils {
// Delay mechanism
public interface DelayCallback{
void afterDelay();
}
public static void delay(int secs, final DelayCallback delayCallback){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
delayCallback.afterDelay();
}
}, secs * 1000); // afterDelay will be executed after (secs*1000) milliseconds.
}
}
我發現StackOverflow上這個方法,但我按一下按鈕後崩潰我的應用程序 有什麼問題?請幫幫忙,我是否應該延遲做的另一種方法,告訴我這 錯誤:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
把你的堆棧跟蹤這裏 –
@LuizFernandoSalvaterra我這樣做是 – Teeracker