2012-12-07 81 views
1

我想我的程序在等待我,而10S真实的,但它不工作 我试图用Thread.sleep(10000);但它不是10秒等待时间 - Android电子

while (true) { 
    for (int i = 0; i < 2; i++) { 
     for (int j = 0; j < 5; j++) { 
      if (matrixVacancy[i][j] == 1) { 
       completeParking(i, j, R.color.vaga_ocupada); 
      } else { 
       completeParking(i, j, R.color.cor_chao); 
      } 
     } 
    } 
    try { 
     Thread.sleep(10000); 
    } catch (InterruptedException ex) { 
    } 

    int a, b, c, d, e, f, g, h, i; 

    a = (int) (Math.random() * 2); // indice i 
    b = (int) (Math.random() * 5); // indice j 
    c = (int) (Math.random() * 2); // tem ou nao carro 

    d = (int) (Math.random() * 2); // indice i 
    e = (int) (Math.random() * 5); // indice j 
    f = (int) (Math.random() * 2); // tem ou nao carro 

    g = (int) (Math.random() * 2); // indice i 
    h = (int) (Math.random() * 5); // indice j 
    i = (int) (Math.random() * 2); // tem ou nao carro 

    matrixVacancy[a][b] = c; 
    matrixVacancy[d][e] = f; 
    matrixVacancy[g][h] = i; 
} 

我该怎么办呢?对于我而言,等10秒?

+2

什么时候你想让你的功能等待?请更多的背景。 – stealthjong

+0

准确地说你是如何做到的。它怎么不起作用?如果您的应用停止响应一段时间,Android会提供您强制关闭它。也许你应该在单独的(非UI)线程上运行该循环? – nullpotent

+1

尝试使用CountDownTimer或简单的计时器为此https://developer.android.com/reference/android/os/CountDownTimer.html https://developer.android.com/reference/java/util/Timer.html –

回答

12

取决于你试图睡觉的线程。你也可以把你的方法放在一个单独的线程中,并在那里做你的方法。这样,你的应用程序将不会挂/休眠

private class TimeoutOperation extends AsyncTask<String, Void, Void>{ 

    @Override 
    protected Void doInBackground(String... params) { 

     try { 
      Log.i(TAG, "Going to sleep"); 
      Thread.sleep(10000); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     Log.i(TAG, "This is executed after 10 seconds and runs on the main thread"); 
     //Update your layout here 
     super.onPostExecute(result); 
    } 
} 

要运行这个操作使用

new TimeoutOperation().execute(""); 
+0

我不能这样做在其他线程,因为我的函数completeParking在LinearLayout中设置背景,并做到这一点我需要在原始线程 –

+0

重写方法onPostExecute(Void结果)在主/ UI线程上运行! :)如果将此代码粘贴到原始线程的类中,则可以访问线性布局。要运行该操作,您应该使用:new TimeoutOperation()。execute(“”); – Oritm

+0

完美!我在onPostExecute。 现在正在工作。谢谢 –

0

首先,我会断点看看你的睡眠是否被称为。其次,当你捕获InterruptException时,我会打印异常。你的睡眠是正确的,所以没有理由不应该工作,所以无论是有人打扰你还是甚至没有进入睡眠功能。

0

变化:

catch (InterruptedException ex) { 
    } 

到:

catch (InterruptedException ex) { 
     ex.printStackTrace(); 
    } 

检查logcat的使确保睡眠不中断。

另外,在调用Thread.sleep打印出已用时间之前和之后,放入一些Log语句。

Logcat是你的朋友。 :)